1

I need to construct a nested object from the result of three Observable streams and display the . All three observables return an array, and two depend on the result of the first. The code I have is as follows:

this.selectActiveFoos$.pipe(
  concatMap(foos => {
    return foos.map(foo => {
      let bars$ = this.barQuery.selectBarsByFooId(foo.id);  
      let bazs$ = this.bazQuery.selectBazsByFooId(foo.id); // these observables return Observable<T[]>
      return forkJoin([bars$, bazs$]).pipe(
        map(([bars, bazs]) => {
          return { 
            foo: foo,
            bars: bars,
            bazs: bazs
          }
        })
      );
    });
  })).subscribe(result => {
    console.log(result);
  });

}

IntelliSense tells me that the type of result is as expected, i.e. a

{ foo: foo, bars: bar[], bazs: baz[] }

however, the console logs an observable as an output. This is really throwing me for a loop. I've searched online for quite some time but I can't seem to find an answer that works with nested arrays of Observable<T[]>.

I would appreciate any advice!

2
  • is it something like this? stackoverflow.com/questions/53344876/… Commented Aug 3, 2020 at 11:31
  • 1
    You're possibly returning [forkJoin(), forkJoin(),..] for each element of the foos array. You need to show what is the structure of that array and how each observable to the forkJoin should look like. Commented Aug 3, 2020 at 11:37

1 Answer 1

2

concatMap must receive an Observable, you can use forkJoin:

this.selectActiveFoos$.pipe(
  concatMap(foos => {
    return forkJoin(foos.map(foo => {
      let bars$ = this.barQuery.selectBarsByFooId(foo.id);  
      let bazs$ = this.bazQuery.selectBazsByFooId(foo.id); // these observables return Observable<T[]>
      return forkJoin([bars$, bazs$]).pipe(
        map(([bars, bazs]) => {
          return { 
            foo: foo,
            bars: bars,
            bazs: bazs
          }
        })
      );
    }));
  })).subscribe(result => {
    console.log(result);
  });
}
Sign up to request clarification or add additional context in comments.

3 Comments

This worked! Thank you very much. If concatMap must receive an observable, why doesn't it show a compile time error?
@E.Mumford accept the answer if it works. what version of typescript and rxjs do you have?
my mistake. First question :) Typescript is ~3.7.5 and RxJs is ~6.5.4

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.