我收到以下错误:
angular2.dev.js:23925 EXCEPTION: TypeError: Cannot read property 'Id' of null in [
{{ product.Id }}
in ProductEditComponent@0:68]
抛出:
//Product-edit.component.ts:
import {Component } from 'angular2/core';
import { IProduct } from './product'
import { ProductService } from './product.service'
import { RouteParams } from 'angular2/router';
@Component({
template:`<div class="wrapper wrapper-content animated fadeInRight ecommerce">
{{ product.Id }}
</div>`,
})
export class ProductEditComponent{
product: IProduct = null;
errorMessage: string;
constructor(private _routeParams: RouteParams, private _productService: ProductService){
}
ngOnInit(): void {
this._productService.getProduct(this._routeParams.get('id'))
.subscribe(
product => this.product = product,
error => this.errorMessage = <any>error);
}
}
产品服务:
getProduct(id: string): Observable<IProduct> {
return this._http.get(this._baseUrl + this._getProductUrl + '/' + id)
.map((response: Response) => <IProduct>response.json())
.do(data => console.log("All: " + JSON.stringify(data)))
.catch(this.handleError);
}
来自服务器的响应:
{"Id":"34d4efcy6","ExternalId":null,"UserId":"testing","ProductProvider":null,"Title":"Flaska vin","Desc":null,"MinDeliveryTime":null,"MaxDeliveryTime":null,"FreightCost":null,"Brand":null}
我搞砸了什么?
答案 0 :(得分:23)
在您的组件中,您将product
初始化为null,然后在模板中引用product.Id
。当Angular最初尝试绘制模板时,在异步调用返回之前发生错误 - 此时product
仍然为空,因此错误:Cannot read property 'Id' of null
。
最直接的解决方案是使用Elvis operator,Angular提供的情况与此类似。您可以在模板中将{{ product.Id }}
替换为{{ product?.Id }}
来使用它。
那就是说,你可能会遇到这种方法的变化检测问题,一般来说,你会用以下方法做得更好:
export class ProductEditComponent{
product: Observable<IProduct>; //product is an Observable
errorMessage: string;
constructor(private _routeParams: RouteParams, private _productService: ProductService){
//product is always defined because you instantiate it in the ctor
this._productService.getProduct(this._routeParams.get('id'));
}
然后,您可以在模板中使用{{(product | async).Id }}
代替{{product.Id}}
,利用AsyncPipe
让角度处理订阅和更新UI的脏工作。