Angular2对象不能设置undefined的属性

rau*_*oob 8 object undefined angular

所以我在Angular2中有这个小应用程序,我正在尝试定义一个对象.这是主要组成部分.

export class ContactComponent  {
    person: {
    firstname: string;
    lastname: string;
}
constructor(private PeopleService: PeopleService){
}

ngOnInit(){

this.PeopleService.fetchData().subscribe(
    data=> {
        this.person.firstname=data.results[0].name.first;
        console.log(this.person.firstname);
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

然后在控制台日志中我得到:

无法设置未定义的属性"firstname"

我无法弄清楚.谢谢.

n00*_*dl3 14

你只是定义了person这里的类型(冒号代表类型注释,例如:) propertyName:Type:

person: {
    firstname: string;
    lastname: string;
}
Run Code Online (Sandbox Code Playgroud)

您应该首先分配一个值,否则,它将是 person

interface Person {
    firstname ? : string; // the "?" makes the property optional, 
    lastname ? : string; //  so you can start with an empty object
}
export class ContactComponent {

    person: Person = {}; // initializing with an empty object

    constructor(private PeopleService: PeopleService) {}

    ngOnInit() {

        this.PeopleService.fetchData().subscribe(
            data => {
                this.person.firstname = data.results[0].name.first;
                console.log(this.person.firstname);
            });
    }
}
Run Code Online (Sandbox Code Playgroud)