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

Opt*_*tte 3 javascript typescript angular2-template angular

我有这个组件:

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
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

在组件的模板中,我有:

<h1>{{category.attributes.name}}</h1>
Run Code Online (Sandbox Code Playgroud)

当我导航到这个组件时,我收到一个错误:

TypeError: cannot read property 'attributes' of undefined
Run Code Online (Sandbox Code Playgroud)

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

Gün*_*uer 10

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

<h1>{{category?.attributes.name}}</h1>
Run Code Online (Sandbox Code Playgroud)

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