![](/img/trans.png)
[英]Typescript/Angular2 TypeError: Cannot read property of undefined
[英]Angular2 - TypeError: Cannot read property 'Id' of undefined in (Typescript)
我收到以下錯誤:
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);
}
}
ProductService:
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
讓角度處理訂閱和更新UI的AsyncPipe
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.