Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular : how to call finally() with RXJS 6

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 ?

like image 747
Sunil Kumar Avatar asked Jul 05 '18 13:07

Sunil Kumar


People also ask

What is finalize in RxJS?

finalizelinkReturns an Observable that mirrors the source Observable, but will call a specified function when the source terminates on complete or error. The specified function will also be called when the subscriber explicitly unsubscribes.

What is the right syntax to filter an Observable in angular 6+?

pipe( filter(num => num % 2 === 0), map(num => num * num)); squareOf2. subscribe( (num) => console. log(num)); The of() method will create and return an Observable from the 1, 2, 3, 4, 5,6 numbers and the pipe() method will apply the filter() and map() operators on each emitted value.

Where do you put catchError?

Always put the “catchError” operator inside a switchMap (or similar) so that it only ends the API call stream and then returns the stream to the switchMap, which continues the Observable.

What is catchError?

RxJS catchError() operator is an error-handling operator used to handle and take care of catching errors on the source observable by returning a new observable or an error.


2 Answers

  • 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().

like image 146
martin Avatar answered Sep 19 '22 18:09

martin


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(); 
like image 44
20B2 Avatar answered Sep 23 '22 18:09

20B2