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>
Elvis运算符阻止Angular求值.attributes...
,除非category
有值。
您也可以通过初始化变量来解决此问题。
在声明时初始化:
export class CategoryDetailComponent implements OnInit{
category: Category = new Category();
...
...
}
组件构造函数中的OR init:
constructor(....) {
this.category = new Category();
}
相关文章:
- 主干中的模型属性未定义
- JavaScript 2d 数组导致“无法读取未定义的属性'未定义'”
- JSON对象属性未定义
- Waypoint的循环,退出循环后属性未定义
- Javascript:错误“无法设置属性”..'未定义”
- 翡翠 - 显示对象属性 - 未定义
- 属性未定义,但控制台.log可以看到它
- JavaScript 对象的属性未定义
- Javascript 对象属性未定义(但属性已设置)
- DOM 元素属性未定义 - jquery / ruby on rails.
- Nodejs JSON 属性未定义
- 错误:窗口打开器的属性未定义
- angular Js:Array.lenght属性未定义
- 正在尝试访问JavaScript对象的属性=未定义
- Marionette属性未定义,请从API获取
- AngularJS作用域属性未定义
- 对象的属性未定义,尽管已指定值
- 为什么我一直收到一个错误,说对象属性未定义
- 对象属性未定义,但我看到它不是
- .map()img src属性未定义