I am following a course that uses angular version 4 however I decided to use version 12.2.10 of angular CLI and version 14.18.1 of Node.
I created a 'contact.ts' model:
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
}
}
and I'm trying to instantiate a new class of it here '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 {
}
}
but impossible to do that. Here is the error message:
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
CodePudding user response:
The error is logic:
You are trying to create a new 'Contact' and, in the constructor of 'Contact', you are saying that you are going to pass 6 parameters (id, nom, prenom, email, tel and photo)
You have to pass this parameters when you try to create, something like:
contact:Contact = new Contact(1,'John','Mr', '[email protected]', ' 34666999666', '/assets/pic01.jpg');
And a little shortcut:
This code do the same as yours (you don't need to declare the attibutes if you declare as publiv/private in the own constructor, like this):
export class Contact{
constructor(
private id:number,
private nom:string,
private prenom:string,
private email:string,
private tel:string,
private photo:string
){}
CodePudding user response:
You either need to pass in all the variables into the Contact
class new Contacts(id, nom, prenom, email, tel, photo)
or mark all the variables as optional.
You can also simplify the constructor, see below.
export class Contact{
constructor(
private id?: number,
private nom?: string,
private prenom?: string,
private email?: string,
private tel?: string,
private photo?: string
){ }
}
two things to note here, by adding ?
it will make that variable optional. Second thing to note is that by marking the variables as private or public, you can avoid needing to set each variable inside the constructor, typescript will do this form you when it compiles.