Angular2对象不能设置undefined的属性

时间:2017-03-21 12:27:57

标签: angular object undefined

所以我在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);
    });
  }
}

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

  

无法设置未定义的属性“firstname”

我无法理解。感谢。

4 个答案:

答案 0 :(得分:11)

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

person: {
    firstname: string;
    lastname: string;
}

您应首先指定一个值,否则将为undefined

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);
            });
    }
}

答案 1 :(得分:0)

创建一个类并继承组件。例如,请参阅以下代码

       export class Person{

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

        ngOnInit(){

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

答案 2 :(得分:0)

首先在onInit()上声明一个人类型的对象。

person p=new person();

答案 3 :(得分:0)

  1. 首先在组件类中创建一个对象。例如:

    employee=new Employee();
    
  2. 然后引用此employee对象