我非常新的角度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