可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I want to iterate [object object] using *ngFor in Angular 2.
The problem is the object is not array of object but object of object which contains further objects.
{ "data": { "id": 834, "first_name": "GS", "last_name": "Shahid", "phone": "03215110224", "role": null, "email": "test@example.com", "picture": **{ <-- I want to get thumb: url but not able to fetch that** "url": null, "thumb": { "url": null } }, "address": "Nishtar Colony", "city_id": 2, "provider": "email", "uid": "test@example.com" } }
I know we can use pipe to iterate the object but how we can iterate further from object to object means data->picture->thum:url.
回答1:
You can use a pipe
@Pipe({ name: 'keys', pure: false }) export class KeysPipe implements PipeTransform { transform(value: any, args: any[] = null): any { return Object.keys(value)//.map(key => value[key]); } }
See also How to use *ngFor with Object?
回答2:
I think the most elegant way to do that is to use the javascript Object.keys like this:
in the Component pass Object to template:
Object = Object;
then in the template:
my key: {{key}} my object {{objs[key] | json}}
回答3:
You have to create custom pipe.
import { Injectable, Pipe } from '@angular/core'; @Pipe({ name: 'keyobject' }) @Injectable() export class Keyobject { transform(value, args:string[]):any { let keys = []; for (let key in value) { keys.push({key: key, value: value[key]}); } return keys; }}
And then use it in your *ngFor
*ngFor="let item of data | keyobject"
回答4:
If you are using a map()
operator on your response,you could maybe chain a toArray()
operator to it...then you should be able to iterate through newly created array...at least that worked for me :)
回答5:
1.Create a custom pipe to get keys.
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'keys' }) export class KeysPipe implements PipeTransform { transform(value: any, args?: any): any { return Object.keys(value); } }
- In angular template file, you can use *ngFor and iterate over your object object
{{key}} {{Obj[key].property}
回答6:
i would do this:
{{item.picture.url}}