How to better catch/do/empty with RXJS 5.5.2 Updates

时间秒杀一切 提交于 2019-12-03 16:06:44

I came up with the following updated code which still works (tested it).

import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/empty';
import {tap} from 'rxjs/operators/tap';
import {catchError} from 'rxjs/operators/catchError';

intercept(req: HttpRequest<any>, next: HttpHandler):   Observable<HttpEvent<any>> {

       return next.handle(req).pipe(
        tap((event: HttpEvent<any>) => {
            if (event instanceof HttpResponse) {
                // do stuff with response if you want
            }
        }),
        catchError((err: HttpErrorResponse) => {
            if ((err.status == 400) || (err.status == 401)) {
                this.interceptorRedirectService.getInterceptedSource().next(err.status);
                return Observable.empty();
            } else {
                return Observable.throw(err);
            }
        })
    );
}

Note:

  • Lettable operators have to be imported with a full import path to reduce the bundle size

    Good: import {catchError} from 'rxjs/operators/catchError'; Bad: import {catchError} from 'rxjs/operators';

  • Static doesn't change respectively they are not lettable (see https://github.com/ReactiveX/rxjs/issues/3059)

  • Static could be only imported once in app.component.ts for the all app (this won't reduce the bundle size but the code will be cleaner)

Building upon the excellent answer from David Dal Buscon, I've also updated Observable.empty and Observable.throw to empty and _throw respectively

import {Observable} from 'rxjs/Observable';
import {empty} from 'rxjs/observable/empty';
import {_throw} from 'rxjs/observable/throw';
import {catchError, tap} from 'rxjs/operators';

intercept(req: HttpRequest<any>, next: HttpHandler):       
  Observable<HttpEvent<any>> {
    return next.handle(req)
      .pipe(
        tap((event: HttpEvent<any>) => {
          if (event instanceof HttpResponse) {
            // do stuff with response if you want
          }
        }),
        catchError((err: HttpErrorResponse) => {
          if ((err.status == 400) || (err.status == 401)) {                         
            this.interceptorRedirectService.getInterceptedSource()
              .next(err.status);
            return empty();
          }

          return _throw(err);
        })
     );
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!