作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我有这个组件:
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
属性未定义,我该如何解决?
最佳答案
模板中的绑定(bind)在 ngOnInit()
之前求值。为防止 Angular 抛出错误,您可以使用
<h1>{{category?.attributes.name}}</h1>
Elvis 运算符会阻止 Angular 评估 .attributes...
除非 category
有值。
关于javascript - Angular 2 : A property set during OnInit is undefined on the template,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36970470/
我是一名优秀的程序员,十分优秀!