我非常新的角度2,我试图做到的是简单的:角2调用API
- 通过路由
- 调用API与类别ID 获取传递的类ID
- 填充变量“类别”的数据与来自API返回和显示分类名
我的观点是简单:
<h3>{{category.name}}</h3>
组件代码:
import { Component, Inject } from '@angular/core';
import { Http } from '@angular/http';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'browse-category',
template: require('./browse-category.component.html'),
styles: [require('./browse-category.component.css')]
})
export class BrowseCategoryComponent {
products: IProduct[];
category: ICategory;
categoryId: number;
constructor(private route: ActivatedRoute, private http: Http, @Inject('ORIGIN_URL') private originUrl: string) {
}
ngOnInit(): void {
this.route.params.subscribe(params => {
this.categoryId = +params['categoryId'];
// get category details
this.http.get(this.originUrl + '/api/Category/' + this.categoryId).subscribe(result => {
var data = result.json().data;
if (data != null && result.status === 200) {
this.category = data;
console.log(this.category);
}
});
});
}
}
如果我禁用了该视图的输出,我能够看到的console.log输出,如果我不这么做,我得到以下错误:
NodeInvocationException:未捕获(承诺):TypeError:无法读取未定义的属性“名称” TypeError:无法读取未定义的属性“名称”
我认为这是因为承诺尚未返回。理想情况下,解决这个问题的最佳方法是什么?
什么是console.log输出? – jhenderson2099