Catch in Observable stops HTTP Calls from Observable.interval

Deadly 提交于 2019-12-13 16:36:01

问题


Observable.interval(10000)
     .switchMap(() => this.http.get(url))
     .catch (err => Observable.empty())
     .subscribe(data => render(data))

Each 10 seconds we make an HTTP call. If an error happens, observable becomes completed, it doesn't make any calls anymore. How to prevent that?


回答1:


That's correct behavior, when a complete or error notification is sent observers unsubscribe and the chain is disposed.

You can use the retry() operator to resubscribe but it's hard to tell what is your goal from this brief description.

Observable.interval(10000)
    .switchMap(() => this.http.get(url))
    .retry()
    .subscribe(data => render(data))



回答2:


takeUntil() of observable.

RxJS implements the takeUntil operator. You can pass it either an Observable or a Promise that it will monitor for an item that triggers takeUntil to stop mirroring the source Observable.

for more info click here




回答3:


Try this:

let dataX = Observable.interval(10000)
 .switchMap(() => this.http.get(url));

let caught = dataX.catch(
Observable.return({
error: 'There was an error in http request'
}))

caught.subscribe((data) => { return render(data) },
// Because we catch errors now, `error` will not be executed
(error) => {console.log('error', error.message)}
 )

if you want you can put any condition when the error comes like

if(!data[error]){
  render(data)
}

I hope that it helps you




回答4:


Observable.interval(10000)
     .switchMap(() => this.http.get(url)
     .map(res => res.json())
     .catch (err => Observable.empty()))
     .subscribe(data => render(data))


来源:https://stackoverflow.com/questions/45715543/catch-in-observable-stops-http-calls-from-observable-interval

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