Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a timeout in Angular 2 when using HTTP + toPromise()?

Tags:

http

angular

I found this answer where the solution proposed is to use Observables to set http requests' timeout.

However my code is structured to use mostly promises (I use observables where I want to have data automatically updated - that's not the case of the API calls).

Here is my code (inspired by Angular 2 tutorial):

makePostRequest(requestUrl:string, requestBody: any, requestOptions?: RequestOptions): Promise<any> {
    requestOptions = requestOptions || new RequestOptions({ headers: this._defaultHeaders });
    return this._http.post(requestUrl, JSON.stringify(requestBody), requestOptions)
        .toPromise()
        .then(this.extractData)
        .catch(this.handleError)
}

How to set a timeout and throw an error (if the timeout expires) that I then catch in .catch() or - alternatively - replicate the exact precise behavior with Observables (including converting the result to a Promise and not monitoring for monitoring for API update(*))?

(*) NOTE: I'm not sure whether Observables keep calling the APIs to check for new data, but that's not the point of my question, I just want to make sure this behavior does not occur.

like image 736
dragonmnl Avatar asked Dec 01 '25 09:12

dragonmnl


2 Answers

I would expect this to do what you want (not tried):

makePostRequest(requestUrl:string, requestBody: any, requestOptions?: RequestOptions): Promise<any> {
    requestOptions = requestOptions || new RequestOptions({ headers: this._defaultHeaders });
    return this._http.post(requestUrl, JSON.stringify(requestBody), requestOptions)
        .timeout(3000, new Error('timeout exceeded'))
        .toPromise()
        .then(this.extractData)
        .catch(this.handleError)
}

From Angular2 timeout in http post request

like image 137
Günter Zöchbauer Avatar answered Dec 06 '25 08:12

Günter Zöchbauer


The solution (right chain + imports) I found:

// ! must import these
...
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';

return this._http.get(requestUrl, requestOptions)
        .timeout(5000, new Error( 'HTTP (GET) timeout for path: ' + requestUrl))
        .map(this.extractData)
        .toPromise()
        .catch(this.handleError);
like image 38
dragonmnl Avatar answered Dec 06 '25 08:12

dragonmnl