Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 timeout in http post request

Tags:

http

post

angular

Is it possible to make a timeout of 3 seconds in a post request ? How ?

My code for the moment

this.http.post('myUrl', 
    MyData, {headers: Myheaders})
        .map(res => res.json())
        .subscribe(
            data => this.ret = data,
            error => console.debug('ERROR', error),
            () => console.log('END')
        );
like image 623
Raph Avatar asked Mar 03 '16 18:03

Raph


3 Answers

You can use the timeout operator like this:

this.http.post('myUrl', 
        MyData, {headers: Myheaders})
         .timeout(3000, new Error('timeout exceeded'))
         .map(res => res.json())
         .subscribe(
           data => this.ret = data,
           error => console.debug('ERROR', error),
           () => console.log('END')
         );
like image 61
Thierry Templier Avatar answered Oct 19 '22 09:10

Thierry Templier


You might need to import timeout like so

import 'rxjs/add/operator/timeout'

I couldn't get it to work without that on rxjs 5.0.1 and angular 2.3.1

Edit 20 April 2018

please refrain from importing operators that way, in rxjs +5.5 you can import operators like this one with

import { timeout } from 'rxjs/operators/timeout';
// Use it like so
stream$.pipe(timeout(3000))

Please checkout this document which explains pipeable operators in great depth.

like image 23
realappie Avatar answered Oct 19 '22 09:10

realappie


I modified the answer of Thierry to get it working with the latest release. It is necessary to remove the second parameter of the timeout function. According to a discussion regarding an angular-cli issue, the timeout function always throws a TimeoutError now.

this.http.post('myUrl', 
    MyData, {headers: Myheaders})
     .timeout(3000)
     .map(res => res.json())
     .subscribe(
       data => this.ret = data,
       error => console.debug('ERROR', error),
       () => console.log('END')
     );
like image 13
Peter Avatar answered Oct 19 '22 08:10

Peter