6

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?

Glenn Utter
  • 2,313
  • 7
  • 32
  • 44

1 Answers1

9

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);
cartant
  • 57,105
  • 17
  • 163
  • 197
  • Sorry. I answered this and then realised I'd misread the question. I've updated the answer. – cartant Aug 17 '16 at 09:00
  • What do I need to import besides `rxjs/add/operator/timeoutWith` to make this work? (the "Rx." part that is). – Glenn Utter Aug 17 '16 at 09:18
  • You will need `import "rxjs/add/observable/defer"` and `import "rxjs/add/observable/throw"`, too. – cartant Aug 17 '16 at 09:19
  • I still get a red squiggly line under "Rx.". – Glenn Utter Aug 17 '16 at 09:23
  • Sorry. Updated the code to use the minimal `Observable` together with the appropriate `import` statements. – cartant Aug 17 '16 at 09:24
  • Thanks. But I get `Proterty 'defer' does not exist on type 'typeof Observable'` using that. – Glenn Utter Aug 17 '16 at 09:27
  • Sorry about that. An invisible space had made it's way before the last "/" in the path. – Glenn Utter Aug 17 '16 at 09:31
  • What's there now ought to be correct. Note that it's `rxjs/add/observable‌` - not `rxjs/add/operator` - for `defer` and `throw`. I'd answered a question earlier using the `import "rxjs/Rx"` and switching back and forth is a little tedious. – cartant Aug 17 '16 at 09:33