我需要使用ngFor将复杂的对象从webapi绑定到Angular5视图,但是我无法解决以下错误:
“找不到类型不同的支持对象'[object Object]' '宾语'。 NgFor仅支持绑定到数组等Iterable。”
我公开了我的代码:
Model.ts
export interface Products {
products: Product[];
}
export interface Product{
id: string;
productStats: ProductStat[];
number: string;
}
export interface ProductStat {
description: string;
relevantProducts: string[];
weight: number;
}
Services.ts
getProducts(productList: string[]): Observable<Products> {
var body = JSON.stringify(productList);
var postHeaders = new HttpHeaders();
postHeaders = postHeaders.set('Content-Type', 'application/json');
return this.httpClient.post<Products>(
this.clientAppService.getProducts, body, { headers: postHeaders})
.map(response => { return response; });
}
Component.ts
productResponse: Products;
getProducts() {
this.productsInputFormatted = this.getProductsInputFormat(this.productsInput);
this.productService.getProducts(this.productsInputFormatted).subscribe(
data => {
this.products = data;
//I tried to convert the following line into array,
//but I get the same error(this.result is
//declared --> result: any[];
//and I changed the value of NgFor in the view)
this.result = Array.of(this.productsResponse);
alert(this.result[0].products[0].id) //I can see the value
});
}
Component.html
<tbody *ngFor="let response of products">
<tr>
<td>{{ response.products.id}}</td>
<td>{{ response.products.number}}</td>
...
任何想法都会有很大帮助。
谢谢
编辑:
还有其他人怀疑有相同的错误,但是在这种情况下,我正确地使用了Observable函数。
我还进行编辑以将解决方案添加到第一个答案中,并提出第二个问题:
错误:
Component.ts:this.products = data;
Component.html:<tbody *ngFor="let response of products">>
解决方案: 在第一个答案中:
Component.ts:this.result = Array.of(this.productsResponse);
Component.html:<tbody *ngFor="let response of results[0].products">
第二个问题
如何访问对象的第二级(productStats.description和productStat.relevantProducts [])?
我可以将嵌套的ngFors与ng-template一起使用吗?
答案 0 :(得分:0)
您需要循环播放
<tbody *ngFor="let response of results[0].products">
<tr>
<td>{{ response.id}}</td>
<td>{{ response.number}}</td>