Angular 2:在OnInit期间设置的属性在模板上未定义

时间:2016-05-01 18:39:02

标签: javascript typescript angular angular2-template

我有这个组件:

export class CategoryDetailComponent implements OnInit{
  category: Category;
  categoryProducts: Product[];
  errorMessage: string;
  constructor(private _categoryService: CategoryService, private _productService: ProductService, private _routeParams: RouteParams ) {}

  ngOnInit() {
    this.getCategoryAndProducts();
  }
  getCategoryAndProducts() {
    let categoryName = this._routeParams.get('name');
    let categoryId = this.routeParams.get('id');
    var params = new URLSearchParams();
    params.set('category', categoryName);

    Observable.forkJoin(
      this._categoryService.getCategory(categoryId),
      this._productService.searchProducts(params)
    ).subscribe(
      data => {
      //this displays the expected category's name.
      console.log("category's name: "+ data[0].attributes.name)
      this.category = data[0];
      this.categoryProducts = data[1];
      }, error => this.errorMessage = <any>error
    )
  }
}

在组件的模板中,我有:

<h1>{{category.attributes.name}}</h1>

当我导航到此组件时,出现错误:

TypeError: cannot read property 'attributes' of undefined

为什么模板上的category属性未定义,我该如何解决?

2 个答案:

答案 0 :(得分:8)

模板中的绑定在ngOnInit()之前进行评估。要防止Angular抛出错误,您可以使用

<h1>{{category?.attributes.name}}</h1>

除非.attributes...有值,否则Elvis运算符会阻止Angular评估category

答案 1 :(得分:4)

您也可以通过初始化变量来解决此问题。

在声明时启动此功能:

export class CategoryDetailComponent implements OnInit{
  category: Category = new Category();
  ...
  ...
}

组件构造函数中的OR init:

constructor(....) {
   this.category = new Category();
}