Hello everyone, tell me how to get rid of subscribe in angular 6 correctly

firstMethod(id: number): Observable<any> { return this.http.get<any>('URL'); } secondMethod(id: number): Observable<any> { return this.http.get<any>('URL'); } myServices.firstMethod(id).suscribe(firstMethodRes => { myServices.secondMethod(firstMethodRes.params).subscribe(secondMethodRes => { ... }); }); 

1 answer 1

Using Promise :

 myServices.firstMethod(id).toPromise().then(({ params }) => { return myServices.secondMethod(params).toPromise(); }).then((secondMethodRes) => { console.log(secondMethodRes); }); 

Using mergeMap || switchMap || concatMap || exhaustMap mergeMap || switchMap || concatMap || exhaustMap mergeMap || switchMap || concatMap || exhaustMap :

 import { mergeMap, switchMap, concatMap, exhaustMap } from 'rxjs/operators'; myServices.firstMethod(id).pipe( mergeMap(({ params }) => myServices.secondMethod(params)) // ИЛИ switchMap(({ params }) => myServices.secondMethod(params)) // ИЛИ concatMap(({ params }) => myServices.secondMethod(params)) // ИЛИ exhaustMap(({ params }) => myServices.secondMethod(params)) ).subscribe((secondMethodRes) => { console.log(secondMethodRes); }); 

Using map + mergeAll || switchAll || concatAll || exhaust map + mergeAll || switchAll || concatAll || exhaust map + mergeAll || switchAll || concatAll || exhaust :

 import { map, mergeAll } from 'rxjs/operators'; myServices.firstMethod(id).pipe( map(({ params }) => myServices.secondMethod(params)), mergeAll() // ИЛИ switchAll() // ИЛИ concatAll() // ИЛИ exhaust() ).subscribe((secondMethodRes) => { console.log(secondMethodRes); }); 
  • Great answer! It would also be nice to describe the difference between switchMap and mergeMap . - Stepan Kasyanenko
  • Well, at least then a reference to the documentation)) - Stepan Kasyanenko
  • @StepanKasyanenko if I am not mistaken, then switchMap completes the previous subscribe, and mergeMap in turn generates a new one for each request - se3os