![](/img/trans.png)
[英](Angular2) JSON data (http.get()) is undefined, and data is not updated in the component
[英]Angular2 Class undefined after calling API via http.get and receiving the correct JSON back
我有以下代碼(基於Angular2 Hero示例),並且我試圖將JSON API調用(AWS)轉換為TypeScript類。
代碼沒有返回錯誤,當我查看response.json()時可以看到對象在那里,但是類產品仍然未定義,有什么想法嗎?
服務文件中的代碼...
getProduct(id: number): Promise<Product> {
const url = `${this.ProductsUrl}/${id}`;
console.log(url);
return this.http.get(url)
.toPromise()
.then(response => response.json().data as Product)
.catch(this.handleError);
}
組件文件中的代碼...
ngOnInit(): void {
this.route.params
.switchMap((params: Params) => this.productsService.getProduct(+params['id']))
.subscribe(product => this.product = product);
}
班級...
export class Product {
Instock: boolean;
Description: string;
CategoryId: number;
Id: number;
ColourOptions: string[];
Name: string;
}
從API調用返回的JSON ...
{
"Instock":true,
"Description":"This is a test description.",
"CategoryId":1,"
Id":1,
"ColourOptions":["Red","Gold","Green"],
"Name":"Test"
}
switchMap
必須返回一個Observable
而不是Promise
,所以編輯getProduct
來返回一個Observable
:
getProduct(id: number): Observable<Product> {
const url = `${this.ProductsUrl}/${id}`;
console.log(url);
return this.http.get(url)
.map(response => response.json().data as Product)
.catch(this.handleError);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.