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

Angular 2: A property set during OnInit is undefined on the 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 属性 未定义,我该如何解决?

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

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

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

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

初始化时声明:

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

或在组件构造函数中初始化:

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