【问题标题】:Angular2 - TypeError: Cannot read property 'Id' of undefined in (Typescript)Angular2 - TypeError:无法读取(Typescript)中未定义的属性“Id”
【发布时间】:2016-05-08 00:23:25
【问题描述】:

我收到以下错误:

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}

我在搞砸什么?

【问题讨论】:

  • this.handleError 中是否有任何错误?

标签: javascript typescript angular angular2-http


【解决方案1】:

在您的组件中,您将 product 初始化为 null,然后在模板中引用 product.Id。当 Angular 最初尝试绘制您的模板时会发生错误,before 您的异步调用返回 - 此时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 让 Angular 根据您的需要处理订阅和更新 UI 的繁琐工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-13
    • 1970-01-01
    • 1970-01-01
    • 2017-09-24
    • 1970-01-01
    • 2017-11-02
    • 1970-01-01
    相关资源
    最近更新 更多