Angular2生成错误 - 无法读取属性' 0'未定义的

时间:2017-04-06 19:49:29

标签: angular

我正在关注英雄之旅教程。而不是getHero()我有一个getCustomer()方法。我收到以下错误:

EXCEPTION: Cannot read property '0' of undefined

为什么我收到此错误的任何想法?我认为handleError()函数可能存在问题。

客户detail.component.ts

getCustomer(id: string): void {
    this.customerService.getCustomer(id)
        .subscribe(
            customer => this.customer = customer,
            error => this.errorMessage = <any>error
        );
}

customer.service.ts

getCustomer(id: string): Observable<Customer> {
    const url = `${this.customerUrl}/${id}`;
    return this.http.get(url)
        .map(this.extractData)
        .catch(this.handleError);
}

private extractData(res: Response) {
    let body = res.json();
    return body || {};
}

private handleError(error: Response | any) {
    // In a real world app, you might use a remote logging infrastructure
    let errMsg: string;

    if (error instanceof Response) {
        const body = error.json() || '';
        const err = body.error || JSON.stringify(body);
        errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
        errMsg = error.message ? error.message : error.toString();
    }

    console.error(errMsg);

    return Observable.throw(errMsg);
}

1 个答案:

答案 0 :(得分:0)

尝试使用async pipe

它应该工作  承诺并返回它发出的最新值。当发出新值时,异步管道标记要检查更改的组件&#34;所以视图将使用新值

进行更新
相关问题