我收到以下错误:
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,因此错误:Cannot read property 'Id' of null
。
最直接的解决方案是使用Elvis运算符,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的繁琐工作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句