gpt4 book ai didi

javascript - Angular 2 : A property set during OnInit is undefined on the template

转载 作者:太空狗 更新时间:2023-10-29 18:03:44 27 4
gpt4 key购买 nike

我有这个组件:

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com