簡體   English   中英

Angular2對象不能設置undefined的屬性

[英]Angular2 object cannot set property of 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”

我無法弄清楚。 謝謝。

你只是定義的類型person在這里(冒號代表類型的注釋,例如: propertyName:Type ):

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

你在這里做的是告訴編譯器該person是一個具有2個字符串屬性firstnamelastname的對象文字。 它定義了可以存儲在該屬性中的內容,而不是它包含的內容。

您應該首先分配一個值,否則,它將是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);
            });
    }
}

創建一個類並繼承組件。 例如,請參閱以下代碼

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

首先在onInit()上聲明person類型的對象。

person p=new person();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM