Ericel
Ericel

Reputation: 299

How to loop through an array, and get some data from database Angular 5

I have the following array in component class (Angular 5):

this.collectionAdmins = ['uid_73hd', 'uid_38ng'];

Since I have tables in my database(firebase) with users info, I want to loop through the this.collectionAdmins array, retrieve each user information from the database, So will be able to display that info in the template.

'uid_73hd': {
  "bio": "about me info",
  "email": "[email protected]",
  "status": "online",
  "uid": "uid_73hd",
  "username": "mary"
},
'uid_38ng': {
  "bio": "about me info",
  "email": "[email protected]",
  "status": "online",
  "uid": "uid_38ng",
  "username": "john"
}

How can I achieve this?

Upvotes: 0

Views: 258

Answers (1)

Tiep Phan
Tiep Phan

Reputation: 12596

Because you’re using Firestore and AngularFire2, we can using following solution:

import { combineLatest } from 'rxjs/observable/combineLatest';

export class YourComponent {
  collectionAdmins = ['uid_73hd', 'uid_38ng'];


  constructor(private afs: AngularFirestore) {

    const abs = this.collectionAdmins
      .map(id => afs.doc<User>(`users/${id}`).valueChanges()); // users table, replace with your real table
    this.collections$ = combineLatest(abs);
  }
}

p/s: some other operators to combine observable: forkJoin, zip. Or Promise.all if you want to using Promise instead of Observable.

Upvotes: 1

Related Questions