简体   繁体   中英

Angular 6 + RxJs - Error handling for concatMap

I'm still learning RxJs, and I'm trying to use concatMap() to NOT use nested subscriptions. I want the first call to run and then delay for a second or two (creating a database record before the second request) before running the second request. I also want to add error handling to each request specifically so I can catch errors for them individually.

So far, I have something that runs request 1, delays, and then runs request 2.

return this.request_1(postData).pipe(
      concatMap(res => of(res).pipe( delay( 2000 ) )),
      concatMap(res => this.request_2(parseInt(data.id), parseInt(model['_id'])) )
    );

What I'm wondering is -

  1. can I use something like catchError() on each request?
  2. is this correct if I want request 1 to complete before the second request runs?

Thanks!

you could add a catchError to each request. but as long as you don't want to mutate the error object i would rather just have one catchError at the end of the pipe. that simply bubbles every error to the subscriber.

the error handling itself can then be done in the subscription

const source = of('World').pipe(
  concatMap(res => of(res).pipe(
    delay(2000),
    map(res => res += ' + concat 1')
  )),
  concatMap(res => of(res).pipe(
    map(res => res.h += ' + concat 2')
  )),
  catchError(err => throwError(err))
);

source.subscribe(
  x => console.log(x),
  error => console.log('error', error)
);

https://stackblitz.com/edit/rxjs-6dign7

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM