我有这个组件:
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
属性未定义,我该如何解决?
答案 0 :(得分:8)
模板中的绑定在ngOnInit()
之前进行评估。要防止Angular抛出错误,您可以使用
<h1>{{category?.attributes.name}}</h1>
除非.attributes...
有值,否则Elvis运算符会阻止Angular评估category
。
答案 1 :(得分:4)
您也可以通过初始化变量来解决此问题。
在声明时启动此功能:
export class CategoryDetailComponent implements OnInit{
category: Category = new Category();
...
...
}
组件构造函数中的OR init:
constructor(....) {
this.category = new Category();
}