A very short tutorial on HTTP GET for Ionic2

Hi All,

I wanted to post a very short explainer for the http.get() call since nearly every article I’ve read has 2 vital parts missing: proper error handling & timeout enforcement.

First, in your *.ts file, include the following libraries and operators:

import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/timeout';

Next, the constructor needs to pass in an HTTP object:

constructor(public _http: Http) {
    // we don't need to do anything here to _http
    // if you need to pass other variables into the constructor, go for it!

Finally, here is a clean example for calling the GET function:

GrabWebData() {
    let path = 'https://xyz.com/foo';
    //let path = 'assets/json/foo.json';  // you can use this for local assets as well :)
    let timeoutMS = 10000;                // force a timeout after n milliseconds

                .map(res => res.json()).subscribe(data => {
                    let response = data;

                    // work with your response data here!

                err => {                      // communication error with server or timeout
                    console.log('  encountered an error');

I hope this can help!


1 Like

Great, I am looking for how to implement the timeout rxjs. and it’s working instead of angular example where the method is => .timeout (3000, new Error(‘Time out’)).