2016-12-13 14 views
0

テンプレート:ngOnInitと非同期データを処理する方法

<h5 class="card-title">{{profile.company}}</h5> 

ProfileComponent:

inline template:3:33 caused by: Cannot read property 'company' of undefined 

私はテンプレートが速く、その後ロードされているので、それはだと思う:

private getRouteParams; 
public profile; 

ngOnInit() { 
    this.getRouteParams = this._route.params.subscribe(params => { 
     this._customerService.getCustomer(params.id) 
      .subscribe(data => this.profile = data[0]) 
    }); 
} 

次のエラーを得ましたngOnInit?どうすればこれを防ぐことができますか?

私はコンソールにデータ[0]を記録します。すべてがうまく見えます。

答えて

1
private getRouteParams; 
public profile:any = { 
company: ''; 
}; 

ngOnInit() { 
    this.getRouteParams = this._route.params.subscribe(params => { 
     this._customerService.getCustomer(params.id) 
      .subscribe(data => this.profile = data[0]) 
    }); 
} 
+0

ありがとうございました。プロファイル用のインターフェイスを使用してこれを防ぐことはできますか? – robert

+0

テンプレート内で非同期パイプやプロファイルを使用する方がよいでしょうか? – robert

+0

Angularチームは、非常に高価な操作であるため、Angular2でフィルターパイプを使用しないことをお勧めしています。 https://angular.io/docs/ts/latest/guide/pipes.html#!#no-filter-pipe – anshuVersatile

関連する問題