Angular2-TypeError:无法读取属性'Id'(Typescript)中未定义的
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);
}
}
产品服务:
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
仍然为空,因此出现错误: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的直接工作。
相关文章:
- 为什么“;未定义的“;在JavaScript中结束循环
- 要求未定义JS回调参数
- 如何检查管道中未定义的项目
- 在gump和nodejs中使用Typescript时,未定义对require和exports的引用
- Angular2-TypeError:无法读取属性'Id'(Typescript)中未定义的
- Visual Studio 2015 Update 2-'中的TypeScript模块;要求'未定义
- Typescript和Browserify-未捕获的TypeError:无法读取属性'步骤'的未定义
- NodeJS'到UpperCase'的未定义(从typescript生成)
- TypeScript运行时错误'未定义'
- 参数“[controllerName]”在转换为TypeScript时不是未定义的NaNunction
- 运行时未定义Typescript模块
- TypeScript:TypeError:无法读取属性'推'的未定义
- 为什么“;这个“;在具有http promise的typescript模块中未定义
- Typescript中的泛型-未定义的T
- 用typescript编写的Angular服务在控制器中是未定义的
- Typescript编译器/Cordova API:检查未定义的全局变量
- typescript中未定义findItemByText
- TypeScript UMD “module”和“define”都是未定义的
- 这一点.$el在编写typescript插件时未定义
- 当typescript属性时,$作用域未定义