I have a rather clunky looking set of code where the data from one observable is feed into another, like such:
let source = this.myService.getFoo() .subscribe(result => { let source2 = this.myService.getMoo(result) .subscribe(result2 => { // do stuff }); });
I know that there are ways to combine and chain but I need data from source to be feed into source2. The nesting of subscribes looks terrible and I'm pretty certain there is a better way to do this.
Thanks!
For transforming items emitted by an Observable into another Observable, you probably want to use the flatMap operator. It creates an inner Observable and flats its result to the outer stream. const source = this. myService .
Make a single observable out of the several ones that need to be executed in parallel (i.e. the many deletions), using forkJoin. Use switchMap to execute one observable after another.
The FlatMap operator transforms an Observable by applying a function that you specify to each item emitted by the source Observable, where that function returns an Observable that itself emits items. FlatMap then merges the emissions of these resulting Observables, emitting these merged results as its own sequence.
To use concatMap in Angular first we need to import it our Component or Service. import { concatMap } from 'rxjs/operators'; In the following code, we have two observables srcObservable which emits 1,2,3,4 & innerObservable which emits 'A','B','C','D' . The ConcatMap receives its values from the srcObservable .
For transforming items emitted by an Observable into another Observable, you probably want to use the flatMap operator. It creates an inner Observable and flats its result to the outer stream.
const source = this.myService .getFoo() .pipe( flatMap(result => this.myService.getMoo(result)) ) .subscribe(result2 => { // do some stuff });
Here are some flat operators you can use that behave differently:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With