簡體   English   中英

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();
  ...
  ...
}

組件構造函數中的OR init:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM