2015-12-01 12:15:14 +01:00
|
|
|
// #docplaster
|
|
|
|
|
|
|
|
// #docregion
|
|
|
|
// #docregion v1
|
2016-01-28 10:22:59 +01:00
|
|
|
import {Injectable} from 'angular2/core';
|
|
|
|
import {Http, Response} from 'angular2/http';
|
|
|
|
import {Hero} from './hero';
|
|
|
|
import {Observable} from 'rxjs/Observable';
|
2015-12-01 12:15:14 +01:00
|
|
|
|
|
|
|
@Injectable()
|
|
|
|
export class HeroService {
|
|
|
|
constructor (private http: Http) {}
|
|
|
|
|
2016-01-28 10:22:59 +01:00
|
|
|
// #docregion endpoint
|
|
|
|
private _heroesUrl = 'app/heroes';
|
|
|
|
// #enddocregion endpoint
|
2015-12-01 12:15:14 +01:00
|
|
|
|
2016-01-28 10:22:59 +01:00
|
|
|
// #docregion methods
|
2015-12-01 12:15:14 +01:00
|
|
|
// #docregion error-handling
|
|
|
|
getHeroes () {
|
2016-02-01 16:49:24 -08:00
|
|
|
// #docregion http-get, http-get-v1
|
2015-12-01 12:15:14 +01:00
|
|
|
return this.http.get(this._heroesUrl)
|
|
|
|
.map(res => <Hero[]> res.json().data)
|
2016-02-01 16:49:24 -08:00
|
|
|
// #enddocregion v1, http-get-v1, error-handling
|
|
|
|
.do(data => console.log(data)) // eyeball results in the console
|
|
|
|
// #docregion v1, http-get-v1, error-handling
|
2016-01-28 10:22:59 +01:00
|
|
|
.catch(this.handleError);
|
2016-02-01 16:49:24 -08:00
|
|
|
// #enddocregion http-get, http-get-v1
|
2015-12-01 12:15:14 +01:00
|
|
|
}
|
2016-01-28 10:22:59 +01:00
|
|
|
// #enddocregion error-handling
|
|
|
|
// #enddocregion v1
|
|
|
|
|
2015-12-01 12:15:14 +01:00
|
|
|
// #docregion addhero
|
|
|
|
addHero (name: string) : Observable<Hero> {
|
|
|
|
return this.http.post(this._heroesUrl, JSON.stringify({ name }))
|
|
|
|
.map(res => <Hero> res.json().data)
|
2016-01-28 10:22:59 +01:00
|
|
|
.catch(this.handleError)
|
2015-12-01 12:15:14 +01:00
|
|
|
}
|
|
|
|
// #enddocregion addhero
|
2016-01-28 10:22:59 +01:00
|
|
|
|
|
|
|
// #docregion v1
|
|
|
|
// #docregion error-handling
|
|
|
|
private handleError (error: Response) {
|
|
|
|
// in a real world app, we may send the server to some remote logging infrastructure
|
|
|
|
// instead of just logging it to the console
|
|
|
|
console.error(error);
|
|
|
|
return Observable.throw(error.json().error || 'Server error');
|
|
|
|
}
|
|
|
|
// #enddocregion error-handling
|
|
|
|
// #enddocregion methods
|
2015-12-01 12:15:14 +01:00
|
|
|
}
|
|
|
|
// #enddocregion
|