我收到以下错误:
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}
我搞砸了什么?
最佳答案
在您的组件中,您将 product
初始化为 null,然后在您的模板中引用 product.Id
。当 Angular 最初尝试绘制您的模板时会发生错误,在您的异步调用返回时 - 此时 product
仍为 null,因此出现错误:无法读取属性'Id' 为 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
来让 Angular 为您处理订阅和更新 UI 的繁琐工作。
关于javascript - Angular2 - 类型错误 : Cannot read property 'Id' of undefined in (Typescript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37094982/