Set timeout for http post

The server delay is completely acceptable in this case. When I was developing my app I did this to configure timeout. After this I tested the app in certain points of my city that doesn’t have a 3g or 4g signal and get timeout error with the server working normally.

This is an example of my code:

.timeout(15000)
.subscribe(res => {
    // request ok
}, error => {
    if (error.message == 'timeout') {
        resolve({ timeout: true })
    } else {
        resolve(false);
    }
})
this.service.method()
.then(data => {
    if (data && !data.timeout) {
        //request ok
    } else {
        //check for time out
        if ( data.timeout ) {
            //timeout problem
        }
    }
}, error => {
    //another request problem
})

I hope it can help

Thank you @diegomachado. This is what i have in my two files now:

Service

myMethod() {
    return this.http.post(myurl, mymessage, myoptions)
     .map(data=> {
          return this.secondMethod(data);
        })
      }

My .ts file:

this.myService.myMethod()
    .timeout(10000)
      .subscribe(
      data => {
     //not the important part
      },
      error =>{
          if (error.message == 'timeout') {
          console.log("timeout yes");
        } else {
          console.log("timeout no");
        }
      })

If i disable the connection, call the api, i get the console.log("timeout no"); error instantly. Before that i see on my console: POST my url net::ERR_INTERNET_DISCONNECTED
If i stay connected but put a sleep method on my server > 10 seconds, i get console.log("timeout no"); just after 10 seconds (if the sleep method is < 10 seconds i get the data as usal).
So the second situation is working fine but i still don’t understand why the first, which is the one i need to resolve, continue to no work.

Maybe when the connection is down Angular breaks my http post? So whatever i put in timeout it will be not called, just guessing now :no_mouth:

Timeout is the time that your request and the server is waiting to complete. If you don’t have a connection, you don’t have to wait. If you turn off your wi-fi and try to access some website on browser, you’ll see an instantly error message.

If you really need to check the connection status, you should use a native plugin for this:
https://ionicframework.com/docs/native/network/

But it can ask for user permission, so it can be not interesting. Unless it is crucial on your app.

2 Likes