预期有 6 个参数,但是 0 received.ts(2554)

6 arguments expected, but 0 received.ts(2554)

我正在学习使用 angular 版本 4 的课程,但是我决定使用 angular CLI 版本 12.2.10 和 Node.

版本 14.18.1

我创建了一个 'contact.ts' 模型:

export class Contact{
    private id:number;
    private nom:string;
    private prenom:string;
    private email:string;
    private tel:string;
    private photo:string;

    constructor(id:number,nom:string,prenom:string,email:string,tel:string,photo:string){
        this.id = id;
        this.nom = nom;
        this.prenom = prenom;
        this.email = email;
        this.tel = tel;
        this.photo = photo
    }

    
}

我正在尝试在此处实例化一个新的 class 'NewContactComponent.ts':

import { Component, OnInit } from '@angular/core';
import { Contact } from 'src/model/model.contact';

@Component({
  selector: 'app-new-contact',
  templateUrl: './new-contact.component.html',
  styleUrls: ['./new-contact.component.css']
})
export class NewContactComponent implements OnInit {

  contact:Contact=new Contact();

  constructor() { }

  ngOnInit(): void {
    
  }

}

但不可能那样做。这是错误消息:

6 arguments expected, but 0 received.ts(2554)
model.contact.ts(10, 17): Aucun argument pour 'id' n'a été fourni.
(alias) new Contact(id: number, nom: string, prenom: string, email: string, tel: string, photo: string): Contact
import Contact

逻辑错误:

您正在尝试创建一个新的 'Contact',并且在 'Contact' 的构造函数中,您说您将传递 6 个参数(id、nom、prenom、email、tel和照片)

当你尝试创建时,你必须传递这个参数,something 喜欢:

contact:Contact = new Contact(1,'John','Mr', 'vincent@myemail.com', '+34666999666', '/assets/pic01.jpg');

还有一个小捷径:

这段代码和你的一样(如果你在自己的构造函数中声明为 publiv/private 则不需要声明属性,像这样):

export class Contact{

constructor(
   private id:number,
   private nom:string,
   private prenom:string,
   private email:string,
   private tel:string,
   private photo:string
){}

您需要将所有变量传入 Contact class new Contacts(id, nom, prenom, email, tel, photo) 或将所有变量标记为可选。

您还可以简化构造函数,见下文。

export class Contact{
  constructor(
    private id?: number,
    private nom?: string,
    private prenom?: string,
    private email?: string,
    private tel?: string,
    private photo?: string
  ){ }
}

这里有两点需要注意,通过添加 ? 将使该变量成为可选变量。第二点要注意的是,通过将变量标记为私有或 public,您可以避免在构造函数中设置每个变量,typescript 将在编译时为您完成此操作。