Reputation: 445
I am new to Angular and Firebase , so please help me. How can i get the UID of the user and also get the whole user list and show it in ngFor , i am using https://github.com/angular/angularfire2/ for connecting with angular
1:
Upvotes: 0
Views: 833
Reputation: 368
I presume, you've multiple user
objects under the /users
node. To access the entire /users
node as an array <User[]>
or simply <any[]>
with the user id
property, please try the following to get the observable which when subscribed would return the array with key (or user id).
@Component({
selector: 'app-root',
template: `
<ul>
<li *ngFor="let user of users$ | async">
ID: {{ user.id}}
</li>
</ul>
`,
})
export class AppComponent {
users$: Observable<any[]>;
constructor(db: AngularFireDatabase) {
this.users$ = db.list('users')
.snapshotChanges()
.pipe(map((users: any[]) => users.map(user => ({ id: user.key, ...user.payload.val() }))));
}
}
Using snapshotChanges()
method returns the firebase node data value along with its metadata as opposed to valueChanges()
which returns only the data payload.
Thus, while using the snapshotChanges()
, we should map (remember to import map
operator from rxjs/operators
) the snapshot and for each user
object in the array, map with the additional property id
and access the auto-assigned firebase key with the key
property value. This, we can access in the template when subscribed.
Here, for every user
object in the array, we are assigning only the id
using the key
from the metadata and the user
object itself using the ...
spread operator. We have not used any other metadata, just to keep the object light.
I hope this works for you.
Upvotes: 2