2017-03-21 25 views
4

この小さなアプリケーションはAngular2にあり、オブジェクトを定義しようとしています。これが主なコンポーネントです。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' を設定することはできません。ありがとう。あなただけの(:propertyName:Typeコロンは、型注釈などの略):ここpersonのタイプを定義している

答えて

4

あなたがそうでなければ、最初の値を割り当てる必要があります

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); 
      }); 
    } 
} 
になります
+0

ありがとうございます!それはうまくいっている! – raulnoob

+0

このhttps://gyazo.com/2ef08d144e87fc28f83fbfe83d974bf3を見ると、HTTPリクエストから50件の結果が得られますが、[1]の2番目のconsole.logは機能しません。どんな考え?それは同じエラー '設定することはできません...' – raulnoob

+0

omg、配列を設定する必要があります、手動で各エントリを作成するつもりはありません... – n00dl3

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

ここに継承されていることはありません... – n00dl3

関連する問題