// RxJS v6+import { throwError, of } from'rxjs';import { catchError } from'rxjs/operators';//emit errorconstsource=throwError('This is an error!');//gracefully handle error, returning observable with error messageconstexample=source.pipe(catchError(val =>of(`I caught: ${val}`)));//output: 'I caught: This is an error'constsubscribe=example.subscribe(val =>console.log(val));
// switchMap in example below can be replaced with mergeMap/concatMap/exhaustMap, the same behaviour appliesimport { throwError, fromEvent, of } from'rxjs';import { catchError, tap, switchMap, mergeMap, concatMap, exhaustMap} from'rxjs/operators';constfakeRequest$=of().pipe(tap(_ =>console.log('fakeRequest')), throwError);constiWillContinueListening$=fromEvent(document.getElementById('continued'),'click').pipe(switchMap(_ =>fakeRequest$.pipe(catchError(_ =>of('keep on clicking!!!')))));constiWillStopListening$=fromEvent(document.getElementById('stopped'),'click').pipe(switchMap(_ => fakeRequest$),catchError(_ =>of('no more requests!!!')));iWillContinueListening$.subscribe(console.log);iWillStopListening$.subscribe(console.log);