Angulandy2
Angulandy2

Reputation: 806

Angular 2 Firebase how to get array in object

I am getting this array from my database :

enter image description here

By this function :

getMembers(){
  this.db.list(`projects/${this.auth.userId}/${this.uploadService.pro.name}/teams/`).snapshotChanges().pipe(
    map(changes =>
      changes.map(c => ({ key: c.payload.key, ...c.payload.val() }))
    )
  ).subscribe((data:any) => 
    console.log(data)
   this.members = data;
    )
}

How to display members in ngFor ?

My try (first ngFor is teams - second one is for members) :

<div *ngFor="let item of teams">
<p>{{item.name}}</p>
<p *ngFor="let member of item.members">{{member}}</p> //does not work
</div>

Error for let member of item.member :

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

Teams are only - name:string - members are in teams.

export Interface Teams {
name: string;
}

export Interface Members {
name: string;
}

At first I upload team - for example "Programmers". Then I add members to that Team. And it looks like :

8468as6d84a6s8d4a6s8d4 {
name: Programmers;
members: {
FirstMember,
SeconndMemeber...
}
}

Upvotes: 2

Views: 2436

Answers (1)

Artyom Amiryan
Artyom Amiryan

Reputation: 2966

you are getting error, because your members is object and object isn't iterable, and *ngFor supports only iterables for example arrays, maps and so on..., so you can:

use Object.keys(), which will return keys of objects in new array,

NOTE that Object isn't accessible in the template, so you should create a pipe or define a method in the component.ts which will do the job, for example

objectKeys(obj) {
    return Object.keys(obj);
}

<div *ngFor="let item of teams">
<p>{{item.name}}</p>
<p *ngFor="let key of objectKeys(item.members)">{{item.members[key].name}}</p>
</div>

or another option you can use Object.values(), which will return values of objects in new array

objectValues(obj) {
   return Object.values(obj);
}
<div *ngFor="let item of teams">
    <p>{{item.name}}</p>
    <p *ngFor="let member of objectValues(item.members)">{{member.name}}</p>
</div>

Upvotes: 3

Related Questions