AlexGo
AlexGo

Reputation: 487

Angular Firebase async inside map function

I want to retrieve something that is asynchronus inside my map function but I don't understand how. The seek data is taken from firestore.

The problem is that I can't use async and await to retrieve seek async.

This is the code:

public quizes: Observable<JobbyAndSeek[]> = responseQuizes.snapshotChanges().pipe(
  map(actions => actions.map(a => {
    const jobby = a.payload.doc.data() as Jobby;
    const seek = this.userService.getUserById(this.seeker ? jobby.idJobber : jobby.idSeeker) as User;
    const data = new JobbyAndSeek(jobby,seek);
    const id = a.payload.doc.id;
    return { id, ...data };
  }))
);

});

Upvotes: 0

Views: 176

Answers (1)

wlf
wlf

Reputation: 3403

You need to use switchmap to handle the subscription to the inner overservable getUserById.

Here is an example, as you didn't supply your classes/interfaces I have guessed and simplified them, I also mocked snapshotChanges to behave like valueChanges but you should be able to see the important concepts which is the use of switchMap and other rxjs operators.

https://stackblitz.com/edit/so-switchmap?file=index.ts

quizes: Observable<JobbyAndUser[]> = this.responseQuizes.snapshotChanges().pipe(
   flatMap(jobbys => jobbys),    // map array to single values
   switchMap(jobby =>            // use switchmap to handle subsciption to user service observable
      this.userService.getUserById(jobby.idJobber).pipe(map(user => ({id: jobby.id, user})),
   toArray()),                   // convert from single values back to array
));

Upvotes: 1

Related Questions