在角度4中创建没有参数的对象

时间:2017-11-27 05:58:36

标签: angular typescript webpack

我目前是Angular 4 Framework的新手。我在组件中创建对象并将其初始化为类的新实例时遇到了困难。我已经将该类导入component.ts文件中。然而,它显示错误是预期的4个参数但有0。任何人都可以请帮助。

我的学生班是:

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 = new Student();

和最后一行

  

this.newStudent = new Student();

我不想实例化newStudent,因为它正在接收应用中不同组件的内容

2 个答案:

答案 0 :(得分:0)

尝试这样:

export class Student {
    constructor(
        public _id?: number,
        public first_name?: string,
        public last_name?: string,
        public email?: string
    ) { }
}

声明像newStudent: Student = new Student();

这样的对象

答案 1 :(得分:0)

您可以将构造函数参数声明为可选,可以在TypeScript中通过添加?来使用此功能。到参数末尾,我们希望是可选的。例如,假设我们希望上面的姓氏参数是可选的:

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