How to make a Http request with timeout?

For example in this situation?

return new Promise((resolve, reject) => {
      let headers = new Headers();
      headers.append('Content-Type', 'application/json');
      this.http.post(this.url + '/api/', JSON.stringify(credentials), { headers: headers }) 
        .subscribe(res => {
          let data = res.json();
          resolve(data);
        }, (err) => {
          reject(err);
        });
    });

This is antipattern soup:

  • You never need to be instantiating Promises
  • You don’t need to stringify POST bodies
  • You don’t need to futz with content type headers

That being said, look into the RxJS timeout operator.

1 Like

so how should it look in your opinion?

Hi

Add .timeout(1000) as operator before subscribe and after get

Next, use .catch to catch errors/timeout to proper follow-up

Regards

Tom

2 Likes

Shouldn’t the code be like

return Observable.from(new Promise((resolve, reject) => {
      let headers = new Headers();
      headers.append('Content-Type', 'application/json');
      this.http.post(this.url + '/api/', JSON.stringify(credentials), { headers: headers }) 
        .subscribe(res => {
          let data = res.json();
          resolve(data);
        }, (err) => {
          reject(err);
        });
    }))

Sorry. just teasing. Couldn’t help it.

Tom

1 Like

import this also
import ‘rxjs/add/operator/timeout’;

return Observable.from(new Promise((resolve, reject) => {
      let headers = new Headers();
      headers.append('Content-Type', 'application/json');
      this.http.post(this.url + '/api/', JSON.stringify(credentials), { headers: headers }).timeout(15000)
        .subscribe(res => {
          let data = res.json();
          resolve(data);
        }, (err) => {
          reject(err);
        });
    }))

try this

Hi

thx. I was actually trying to be funny, which evidently didn’t work out.

It doesn’t make sense to put an observable (http.post) in a Promise. Even worse:convert that one back to Observable.

The code should be more like

return this.http.post( ....)
             .timeout(15000)
             .catch((err:Response) => {
                      let details = err.json();
                      return Observable.throw(new Error(details));
                  })
             .map(res=>res.json())
             .subscribe( (data)=>{ .. do something }, (done)=>{.. do something }, (error)=>{.. do something })

And I didn’t need to import the operator.

This worked fine for me:

import { Observable } from "rxjs/Rx";

Regards

Tom

1 Like

You should use Observables instead of promises.
Observables is the good approach

1 - https://angular-2-training-book.rangle.io/handout/observables/observables_vs_promises.html

2 - https://stackoverflow.com/questions/37364973/angular-promise-vs-observable

1 Like

and how should I call this function?

It is simple to call a function.

Import the service in the class where you want call the function.
Make a object of that service in your constructor.

then you will only call it by

this.servicename.functionname(arguments to be passed);

hi funnhuman

greeting for the day !

i think this would help you

getPeople() {
  return http.get('http://localhost:3000/users')
      .timeout(2000)
      .map(response => response.json());
  }
}

foo() {
  this.subscription = getPeople.subscribe(data => this.people = data)
}

// to cancel manually
cancel() {
  this.subscription.unsubscribe();
}

url

1 Like

Check out the size of your app binary doing it that way versus importing the operator and Observable from Observable. When you import Observable from the monolithic Rx or rxjs, you end up with the entire kitchen sink. Last I checked, it was about 600KB.

1 Like

Hi may i know where should this code applied in the app . issit app.component.ts file ?

I needed to this, this is what I did to achieve it:

return new Promise((resolve, reject) => {
    this.http.get(url)
        .pipe(timeout(10000))
        .toPromise()
        .then((getRequestResponse: APIResponseModel) => {
            if (!environment.production) { console.log(getRequestResponse); }
                resolve(getRequestResponse);
            })
        .catch((error) => {
            if (!environment.production) { console.log(error); }
                reject(error);
            });
});