2015-12-01 12:15:14 +01:00
|
|
|
/* Promise version */
|
|
|
|
// #docplaster
|
|
|
|
|
|
|
|
// #docregion
|
2016-01-28 10:22:59 +01:00
|
|
|
import {Injectable} from 'angular2/core';
|
|
|
|
import {Http, Response} from 'angular2/http';
|
2016-02-01 19:52:14 -08:00
|
|
|
import {Headers, RequestOptions} from 'angular2/http';
|
2016-01-28 10:22:59 +01:00
|
|
|
import {Hero} from './hero';
|
2015-12-01 12:15:14 +01:00
|
|
|
|
|
|
|
@Injectable()
|
|
|
|
export class HeroService {
|
|
|
|
constructor (private http: Http) {}
|
|
|
|
|
2016-02-17 18:13:57 +01:00
|
|
|
// URL to web api
|
|
|
|
private _heroesUrl = 'app/heroes.json';
|
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
|
|
|
getHeroes () {
|
|
|
|
return this.http.get(this._heroesUrl)
|
|
|
|
.toPromise()
|
2016-02-01 19:52:14 -08:00
|
|
|
.then(res => <Hero[]> res.json().data, this.handleError)
|
|
|
|
.then(data => { console.log(data); return data; }); // eyeball results in the console
|
2015-12-01 12:15:14 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
addHero (name: string) : Promise<Hero> {
|
2016-02-01 19:52:14 -08:00
|
|
|
let body = JSON.stringify({ name });
|
|
|
|
let headers = new Headers({ 'Content-Type': 'application/json' });
|
|
|
|
let options = new RequestOptions({ headers: headers });
|
|
|
|
|
|
|
|
return this.http.post(this._heroesUrl, body, options)
|
2015-12-01 12:15:14 +01:00
|
|
|
.toPromise()
|
2016-01-28 10:22:59 +01:00
|
|
|
.then(res => <Hero> res.json().data)
|
|
|
|
.catch(this.handleError);
|
2015-12-01 12:15:14 +01:00
|
|
|
}
|
2016-01-28 10:22:59 +01:00
|
|
|
|
|
|
|
private handleError (error: any) {
|
2016-02-21 11:42:10 -05:00
|
|
|
// in a real world app, we may send the error to some remote logging infrastructure
|
2016-01-28 10:22:59 +01:00
|
|
|
// instead of just logging it to the console
|
|
|
|
console.error(error);
|
|
|
|
return Promise.reject(error.message || error.json().error || 'Server error');
|
|
|
|
}
|
|
|
|
// #enddocregion methods
|
2015-12-01 12:15:14 +01:00
|
|
|
}
|
|
|
|
// #enddocregion
|