0

I have a fuction inside my service which returns an observable array of entity ids and I have another function, which takes an entity id, with which I can get detailed information of an entity as an observable.

Now I want to requests all entity ids with the first function an then pipe those ids one by one into the second function to get one big observable with all my detailed entity informations.

Just to talk about the same functions:

this.api.getEntities()   -> gets all entity ids

this.api.getEntity(id)   -> gets information of a single entity

This is what i tried so far but its just working with when there is only one entity, with two or more entities id = 1, 2.

this.entities$ = this.api.getEntities().pipe(switchMap(id => this.api.getEntity(id)));

My working solution now is:

this.entities$ = this.api.getEntities().pipe(switchMap(ids => forkJoin(ids.map(id => this.api.getEntity(id)))));
7
  • Please share the return types of each of your method Commented Jun 30, 2021 at 18:33
  • return type is Observable<any> Commented Jun 30, 2021 at 18:35
  • Well, first define the correct types then! They should be Observable<Array<number>> and Observable<Entity> probably. Commented Jun 30, 2021 at 18:38
  • okay did that but still I don't know how to chain those two Commented Jun 30, 2021 at 18:41
  • Not really, the answer uses .map on an observable but I can't use .map I have to use .pipe(map( it => ........)) Commented Jun 30, 2021 at 18:53

1 Answer 1

1

Inspired by RxJs Array of Observable to Array

return this.api.getEntities()
  .pipe(
    flatMap((ids: Array<number>) => {
      return Observable.forkJoin(
        ids.map((id: number) => this.api.getEntity(id))
      );
    })
  )
  .subscribe((entities: Array<Entity>) => {
    // Do something
  })
Sign up to request clarification or add additional context in comments.

1 Comment

flatMap was renamed to mergeMap, but otherwise great answer!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.