angular2 / RxJS - 如何从subscribe()内部重试

时间:2016-10-21 11:16:41

标签: angular rxjs observable angular2-observables

这是我的代码:

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() } }
)

如果发生异常,它将被发送到API中的函数然后返回true如果问题得到解决(例如令牌刷新),它只需要在修复后再次重试

我无法弄清楚如何让它重试。

2 个答案:

答案 0 :(得分:6)

.getCompanies()添加.retryWhen之后的.map来电中:

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

在此示例中,observable在2次失败后完成(errorCount < 2)。

答案 1 :(得分:0)

你的意思是这样的吗?

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)
        }
    }
}