我有以下代码(基于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"
}
答案 0 :(得分:2)
case "FOO_BAR":
const oldList = {...state.list};
const newKey1Value = action.payload.key.value;
oldList.key1.value = oldList.key1.value.concat(newKey1Value);
const newKey1fetching = action.payload.key.fetching;
oldList.key1.fetching = newKey1fetching;
return {
...state,
list: oldList
}
&#39;回调必须返回switchMap
而不是Observable
,因此请修改Promise
以返回getProduct
:
Observable