Angular 2 rxjs timeout callback

2019-01-28 05:26发布

I want to provide feedback to the user if a timeout event on a HTTP call happens.

I tried this:

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

But that fires the feedback service as soon as the HTTP call is made.

How do I fire the service when the timeout kicks in?

1条回答
你好瞎i
2楼-- · 2019-01-28 06:22

Assuming _feedbackService.error returns an Error, you should be able to do what you need with the timeoutWith and defer operators:

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);
查看更多
登录 后发表回答