[英]angular 4 iterate over objects of objects for dynamic data
I am trying to iterate over objects of object 我正在尝试遍历对象的对象
Here is response json I will get 这是我将得到的响应json
{
"123445": {
"displayName": "abcd",
"items": [
{
"id": "e7363730-552d-4943-a3b8-082db653fc16",
"name": "xyz",
"displayName": "xyd",
"price": "75",
"quntity": "100"
},
{
"id": "302fda08-502d-4f5a-98b8-cbca34f8e186",
"name": "pqr",
"displayName": "pqr",
"price": "60",
"quntity": "100"
}
]
}
}
Here is what am trying 这是正在尝试的
<div *ngFor="let key of generateKeys(products | async)">
<div *ngFor="let product of products[key].items | async">{{ product | json}}</div>
</div>
and here is funtion which will return keys from products object 这是将从产品对象返回键的功能
generateKeys(obj) {
return obj ? Object.keys(obj) : null
}
But while rendering HTML template it is giving err that 但是在渲染HTML模板时,它给了err
Cannot read property 'items' of undefined
Am I missing something, please suggest. 我错过了什么吗,请提出建议。
import 'rxjs/add/operator/share';
@Component({...})
export class FooComponent{
products$: Observable<{[id:string]:any}>;
constructor(private _fooService: FooService){
this.products$ = _fooService.getProducts().share(); //set observable
}
get keys$(){
return this.products$
.map(map => Object.keys(map));
}
getProducts$(key:string){
// TODO check key existence
return this.products$
.map(map => map[key])
.map(obj => obj.items || [])
}
}
<div *ngFor="let key of keys$ | async">
<div *ngFor="let product of getProducts$(key) | async">{{ product | json}}</div>
</div>
Another, less rjxs oriented approach, would be: 另一种不太面向rjxs的方法是:
@Component({...})
export class FooComponent{
products$: Observable<{[id:string]:any}>;
constructor(private _fooService: FooService){
this.products$ = _fooService.getProducts(); //set observable
}
getKeys(map: any): string[]{
let result = [];
if(map){
result = Object.keys(map);
}
return result;
}
getProducts(key:string,map: any): any[] {
let result [];
if(map & map[key]){
result = map[key];
}
return result;
}
}
<ng-container *ngIf="products$| async as products">
<div *ngFor="let key of getKeys(products)">
<div *ngFor="let product of getProducts(key,products)">{{ product | json}}
</div>
</div>
</ng-container>
Based on my understanding you can try this 根据我的理解,您可以尝试一下
template 模板
<ng-container *ngIf="products | async as products">
<div *ngFor="let key of generateKeys(products)">
<span>{{key}}</span>
<div *ngFor="let product of getProducts(products,key)">
<span>{{product.id}}</span>
</div>
</div>
</ng-container>
the function generateKeys will returns keys from object 函数generateKeys将返回对象的键
generateKeys(obj) {
return obj ? Object.keys(obj) : null
}
and function getProducts will return items from products 和功能getProducts将返回产品中的项目
getProducts(productsList, key: string) {
return key ? productsList[key].items : null
}
hope this will resolve your issue. 希望这能解决您的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.