Created
September 14, 2017 06:19
-
-
Save AkshayRana92/fc0f71ac990afadeffaa6b403db91639 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {Headers, Http} from '@angular/http'; | |
import {Injectable, Inject} from '@angular/core'; | |
import {Observable} from 'rxjs/Observable'; | |
import 'rxjs/add/observable/of'; | |
import 'rxjs/add/observable/throw'; | |
import 'rxjs/add/operator/catch'; | |
import 'rxjs/add/operator/map'; | |
@Injectable() | |
export class AppService { | |
private userDataURL: string; | |
constructor(private http: Http) { | |
this.userDataURL = 'https://jsonplaceholder.typicode.com/users' | |
} | |
getData() { | |
let headers = new Headers({ | |
'Content-Type': 'application/json' | |
}); | |
return this.http | |
.get(this.userDataURL, {headers: headers}) | |
.map(this.extractData) | |
.catch(this.handleError); | |
} | |
private extractData(res: any) { | |
let body = res.json(); | |
return body || {}; | |
} | |
private handleError(error: any) { | |
let errMsg: string; | |
try { | |
if(JSON.parse(error._body)) { | |
errMsg = JSON.parse(error._body); | |
} else { | |
errMsg = 'Something went wrong. Please try again later.'; | |
} | |
} catch(e){ | |
errMsg = 'Something went wrong. Please try again later.'; | |
} | |
return Observable.throw(new Error(errMsg)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment