angular2 / RxJS - how to retry from inside subscribe()

老子叫甜甜 提交于 2019-12-21 17:35:13

问题


this is my code:

this._api.getCompanies().subscribe(
    res => this.companies = JSON.parse(res),
    exception => {if(this._api.responseErrorProcess(exception)) { // in case this retured TRUE then I need to retry() } }
)

in case an exception happened, it will be sent to a function in the API then return true if the problem is fixed (like token refreshed for example) and it just needs to retry again after its fixed

I could not figure out how to make it retry.


回答1:


In your .getCompanies() call right after the .map add a .retryWhen:

.retryWhen((errors) => {
    return errors.scan((errorCount, err) => errorCount + 1, 0)
                 .takeWhile((errorCount) => errorCount < 2);
});

In this example, the observable completes after 2 failures (errorCount < 2).




回答2:


You mean something like this?

this._api.getCompanies().subscribe(this.updateCompanies.bind(this))

updateCompanies(companies, exception) {
    companies => this.companies = JSON.parse(companies),
    exception => {
        if(this._api.responseErrorProcess(exception)) {
            // in case this retured TRUE then I need to retry()
            this.updateCompanies(companies, exception)
        }
    }
}


来源:https://stackoverflow.com/questions/40175255/angular2-rxjs-how-to-retry-from-inside-subscribe

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