如何使用ngOnInit处理异步数据

时间:2016-12-13 13:46:26

标签: angular

模板:

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

ProfileComponent:

private getRouteParams;
public profile;

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

出现以下错误:

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

我认为这是因为模板的加载速度比ngOnInit快?我该如何防止这种情况?

我将数据[0]记录到控制台。一切都很好。

1 个答案:

答案 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])
    });
 }
相关问题