Skip to content

Instantly share code, notes, and snippets.

@peterbsmyth
Last active May 9, 2017 21:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peterbsmyth/6ac466b90acf32e8f6853bcc5e2c87ba to your computer and use it in GitHub Desktop.
Save peterbsmyth/6ac466b90acf32e8f6853bcc5e2c87ba to your computer and use it in GitHub Desktop.
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