necati
necati

Reputation: 187

how to execute observable in array Angular?

I have an array variable named users. it contains users id elements.

users=[uid1, uid2, uid3];

and I want to map this array and get users info from Firestore like this:

let userInfo;
userInfo = users.map((element:any) => {       
    if (element){
        this.afsService.doc(`user/${element}`).subscribe(user => {
            return {...user}
        });    
    }
...

when this code worked, I got this error:

You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.

so my question; how to execute Observable in array iterate?

Upvotes: 0

Views: 76

Answers (2)

necati
necati

Reputation: 187

thaks @Moxxi I ca run my codes with helps. this my codes; forkJoin not work so I used combineLatest instead of it. anf filter(Boolean) worked with pipe.

 this.usersInfo$= combineLatest(
          users.map((user:any)=>this.afs.doc(`users/${user.uid}`).valueChanges()
        )).pipe(map(x=>x.filter(Boolean)))

Upvotes: 1

MoxxiManagarm
MoxxiManagarm

Reputation: 9134

You can map your id's to an array of observable and execute them with an combination operator liek forkJoin or combineLatest. The subscription will bring you an array of the results

userIds = [uid1, uid2, uid3];

userInfos$ = forkJoin(userIds.filter(Boolean).map(userId => this.afsService.doc(`user/{userId}`)));

userInfos$.subscribe(console.info);

Upvotes: 0

Related Questions