0

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 };
  }))
);

});

1 Answer 1

1

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
));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.