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.
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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With