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

问题描述:

我有这个组成部分:

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
    )
  }
}

在组件的模板中,我有这个:

In the component's template I have this:

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

导航到该组件时,出现错误:

When I navigate to this component, I get an error:

TypeError: cannot read property 'attributes' of undefined

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

why is the category property on the template undefined and how can I solve this?

模板中的绑定在ngOnInit()之前评估.为了防止Angular引发错误,您可以使用

The bindings in the template are evaluated before ngOnInit(). To prevent Angular to throw an error you can use

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

除非category具有值,否则Elvis运算符可防止Angular计算.attributes....

The Elvis operator prevents Angular evaluating .attributes... unless category has a value.