在angular 4中创建没有参数的对象
我目前是Angular 4框架的新手。在组件中创建对象并将其初始化为类的新实例时,我遇到了困难。我已经将该类导入到component.ts文件中。但它显示的错误与预期的一样,有4个参数,但有0个。谁能帮忙吗 我的学生班是:在angular 4中创建没有参数的对象,angular,typescript,webpack,Angular,Typescript,Webpack,我目前是Angular 4框架的新手。在组件中创建对象并将其初始化为类的新实例时,我遇到了困难。我已经将该类导入到component.ts文件中。但它显示的错误与预期的一样,有4个参数,但有0个。谁能帮忙吗 我的学生班是: export class Student { constructor( public _id: number, public first_name :string, public last_name: string, public e
export class Student {
constructor(
public _id: number,
public first_name :string,
public last_name: string,
public email : string
){}
}
错误在组件文件中:
export class StudentNewComponent implements OnInit {
newStudent= new Student();
createStudentEvent= new EventEmitter();
constructor() { }
ngOnInit() {
}
create(){
this.createStudentEvent.emit(this.newStudent);
this.newStudent = new Student();
}
}
在上面的代码段中,第二行有错误
newStudent=新学生()
最后一行呢
this.newStudent=新学生()
我不想实例化newStudent,因为它正在从应用程序中的不同组件接收内容
export class Student {
constructor(
public _id?: number,
public first_name?: string,
public last_name?: string,
public email?: string
) { }
}
像这样声明对象newStudent:Student=newStudent()代码>像这样尝试:
export class Student {
constructor(
public _id?: number,
public first_name?: string,
public last_name?: string,
public email?: string
) { }
}
像这样声明对象newStudent:Student=newStudent()代码>您可以将构造函数参数声明为可选参数,通过添加?在参数末尾,我们希望是可选的。例如,假设我们希望上面的姓氏参数是可选的:
function buildName(firstName: string, lastName?: string) {
if (lastName)
return firstName + " " + lastName;
else
return firstName;
}
let result1 = buildName("Bob"); // works correctly now
let result2 = buildName("Bob", "Adams", "Sr."); // error, too many parameters
let result3 = buildName("Bob", "Adams"); // ah, just right
您可以将构造函数参数声明为可选参数,通过添加?在参数末尾,我们希望是可选的。例如,假设我们希望上面的姓氏参数是可选的:
function buildName(firstName: string, lastName?: string) {
if (lastName)
return firstName + " " + lastName;
else
return firstName;
}
let result1 = buildName("Bob"); // works correctly now
let result2 = buildName("Bob", "Adams", "Sr."); // error, too many parameters
let result3 = buildName("Bob", "Adams"); // ah, just right
感谢@Chandru,该错误已在IDE中消失,但使用ng serveThanks时webpack未能编译@Chandru,该错误已在IDE中消失,但使用ng serve时webpack未能编译