Angular2生成错误-无法读取属性';0';未定义的
我正在学习《英雄之旅》教程。我没有使用Angular2生成错误-无法读取属性';0';未定义的,angular,Angular,我正在学习《英雄之旅》教程。我没有使用getHero()而是使用getCustomer()方法。我得到以下错误: EXCEPTION: Cannot read property '0' of undefined 你知道我为什么会犯这个错误吗?我认为handleError()函数可能有问题 customer-detail.component.ts getCustomer(id:string):无效{ this.customerService.getCustomer(id) .订阅( custom
getHero()
而是使用getCustomer()
方法。我得到以下错误:
EXCEPTION: Cannot read property '0' of undefined
你知道我为什么会犯这个错误吗?我认为handleError()函数可能有问题
customer-detail.component.ts
getCustomer(id:string):无效{
this.customerService.getCustomer(id)
.订阅(
customer=>this.customer=customer,
error=>this.errorMessage=错误
);
}
客户服务
getCustomer(id:string):可观察{
常量url=`${this.customerUrl}/${id}`;
返回此.http.get(url)
.map(此.extractData)
.接住(这个.把手错误);
}
私有数据(res:Response){
让body=res.json();
返回体| |{};
}
私有句柄错误(错误:响应|任意){
//在现实世界的应用程序中,您可能会使用远程日志记录基础设施
让errMsg:string;
if(响应的错误实例){
const body=error.json();
const err=body.error | | JSON.stringify(body);
errMsg=`${error.status}-${error.statusText | |'''}${err}`;
}否则{
errMsg=error.message?error.message:error.toString();
}
控制台错误(errMsg);
返回可观察抛出(errMsg);
}
尝试使用
应该有用的
承诺并返回它发出的最新值。当发出一个新值时,异步管道会将要检查的组件标记为“更改”,以便使用新值更新视图
应该有用的
承诺并返回它已发出的最新值。当发出新值时,异步管道会标记要检查的组件以进行更改,“因此将使用新值更新视图”is''}${err}
是errMsg=..
line中的有效语法吗?'}${err}
是errMsg=..
line中的有效语法吗?
getCustomer(id: string): void {
this.customerService.getCustomer(id)
.subscribe(
customer => this.customer = customer,
error => this.errorMessage = <any>error
);
}
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);
}