Last active
May 9, 2017 21:17
-
-
Save peterbsmyth/6ac466b90acf32e8f6853bcc5e2c87ba to your computer and use it in GitHub Desktop.
This file contains hidden or 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 { Injectable } from '@angular/core'; | |
import { Http, Response } from '@angular/http'; | |
import { Observable } from 'rxjs/Observable'; | |
import 'rxjs/add/operator/catch'; | |
import 'rxjs/add/operator/map'; | |
@Injectable() | |
export class UserService { | |
private usersUrl = 'https://jsonplaceholder.typicode.com/users'; | |
constructor (private http: Http) {} | |
getUsers(): Observable<any[]> { | |
return this.http.get(this.usersUrl) | |
.map(this.extractData) | |
.catch(this.handleError); | |
} | |
private extractData(res: Response) { | |
let body = res.json(); | |
return body || { }; | |
} | |
private handleError (error: Response | any) { | |
// In a real world app, you might use a remote logging infrastructure | |
let errMsg: string; | |
if (error instanceof Response) { | |
const body = error.json() || ''; | |
const err = body.error || JSON.stringify(body); | |
errMsg = `${error.status} - ${error.statusText || ''} ${err}`; | |
} else { | |
errMsg = error.message ? error.message : error.toString(); | |
} | |
console.error(errMsg); | |
return Observable.throw(errMsg); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment