0
我有以下代碼(基於Angular2 Hero示例),並試圖將JSON API調用(AWS)轉換爲TypeScript類。Angular2 Class通過http.get調用API並接收到正確的JSON後未定義
該代碼沒有返回任何錯誤,並且我可以看到該對象在那裏,當我查看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;
}
的JSON從返回API調用...
{
"Instock":true,
"Description":"This is a test description.",
"CategoryId":1,"
Id":1,
"ColourOptions":["Red","Gold","Green"],
"Name":"Test"
}
你不能訂閱'Promise' – n00dl3
這看起來正確 – eddyP23
eddyP23,你的意思代碼看起來是正確的? n00dle - 我從Angular2網站上的英雄示例中獲取代碼,是不正確的? – edge2