Angular 2 rxjs超时回调

时间:2016-08-17 07:16:56

标签: angular timeout rxjs

如果HTTP调用发生超时事件,我想向用户提供反馈。

我试过了:

return this._http
                .post(apiUrl + 'Search/Everything', params, {withCredentials: true, headers: this.headers})
                .timeout(5000, this._feedbackService.error("Custom error message"))
                .map((response: Response) => response.json().data);

但是,只要进行HTTP调用,就会触发反馈服务。

如何在超时启动时触发服务?

1 个答案:

答案 0 :(得分:8)

假设_feedbackService.error返回Error,您应该可以使用timeoutWithdefer运营商执行所需操作:

import "rxjs/add/observable‌​/defer";
import "rxjs/add/observable‌​/throw";
import "rxjs/add/operator/timeoutWith";
import { Observable } from "rxjs/Observable‌​";

return this._http
    .post(apiUrl + 'Search/Everything', params, {withCredentials: true, headers: this.headers})
    .timeoutWith(5000, Observable.defer(() => Observable.throw(this._feedbackService.error("Custom error message"))))
    .map((response: Response) => response.json().data);