Angular 2 rxjs time callback

I want to provide feedback to the user if a timeout event occurs in an HTTP call.

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 this calls the feedback service as soon as the HTTP call is made.

How do I start a service when a timeout is triggered?

+4
source share
1 answer

Assuming it _feedbackService.errorreturns Error, you should do what you need with timeoutWithand defer:

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);
+5
source

Source: https://habr.com/ru/post/1651498/


All Articles