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
this._http.get(path)
.timeout(timeoutMS)
.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!
Ryan