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

Angular 2: A property set during OnInit is undefined on the template

本文关键字:属性 未定义 OnInit Angular 设置      更新时间:2023-09-26

我有这个组件:

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>

Elvis运算符阻止Angular求值.attributes...,除非category有值。

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

在声明时初始化:

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

组件构造函数中的OR init:

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