Angular 2:在 OnInit 期间设置的属性在模板上未定义 [英] Angular 2: A property set during OnInit is undefined on the template

查看:26
本文介绍了Angular 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.

这篇关于Angular 2:在 OnInit 期间设置的属性在模板上未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆