Search code examples
rxjsreactive-programmingobservableangular2-httponerror

rxjs switchMap onerror behavior


I have a confusion about switchMap in rxjs Observable:

for example i have next code:

Observable.fromEvent(button, 'click') .switchMap(() => Observable.fromPromise(fetch('http://return-error.com'))) .subscribe( (response) => { console.log(response); }, (error) => { console.log(error); } ); If I get error from fetch, subscription is interrupted. So is there way to handle it to not create new subscription for any error?

I have even tried to catch error and return Observable, but subscription is interrupted anyway.

upd: how to deal with angular 2 http.get instead of fetch?


Solution

  • It's always more helpful if you make a Bin when asking these questions. I did it for you on this one.

    You simply need to swallow the error in the fetch call. E.g.

    fetch('bad-url').catch(err => 'Error but keep going')

    Here's the demo. Click the document (output) to fire the event.

    http://jsbin.com/vavugakere/edit?js,console,output

    (You'll need a browser with native Fetch implementation or it'll throw an error)