Angular : how to call finally() with RXJS 6

落花浮王杯 提交于 2019-12-30 01:47:16

问题


I was using RXJS 5, now as I upgraded it to 6, I am facing some problems.

Previously I was able to use catch and finally but as per update catch is replaced with catchError (with in the pipe) now how to use finally?

Also I have some questions :

Do I need to change throw->throwError (in below code Observable.throw(err);)

import { Observable, Subject, EMPTY, throwError } from "rxjs";
import { catchError } from 'rxjs/operators';

return next.handle(clonedreq).pipe(
          catchError((err: HttpErrorResponse) => {
        if ((err.status == 400) || (err.status == 401)) {
            this.interceptorRedirectService.getInterceptedSource().next(err.status);
            return Observable.empty();
        } else {
            return Observable.throw(err);
        }
       }) 
        //, finally(() => {
        //  this.globalEventsManager.showLoader.emit(false);
        //});
      );

Also how to use publish().refCount() now ?


回答1:


  • use throwError instead of Observable.throw, see https://github.com/ReactiveX/rxjs/blob/master/docs_app/content/guide/v6/migration.md#observable-classes

  • finally was renamed to finalize and you'll use it inside pipe() among other operators.

  • the same with publish() and refCount(). Both are operators you'll use inside pipe().




回答2:


Need to import finalize from rxjs/operators.

import { finalize } from 'rxjs/operators';

Then finalize is used inside the pipe(),

observable()
    .pipe( 
         finalize(() => {
              // Your code Here
         })
     )
    .subscribe();



回答3:


According to official document, You should change your code like this to avoid compile error: (You must throw exception in catchError method. finalize callback method has no argument.)

import { catchError, finalize } from 'rxjs/operators';

return next.handle(clonedreq).pipe(
  catchError(error => {
    console.log('error occured:', error);
    throw error;
  }),
  finalize(() => {
    console.log('finalize')
  })
);

It is successfully compiled in Angular CLI: 7.1.4.



来源:https://stackoverflow.com/questions/51192925/angular-how-to-call-finally-with-rxjs-6

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