2015-12-01 12:15:14 +01:00
|
|
|
// #docplaster
|
|
|
|
|
// #docregion
|
2016-05-17 21:25:41 -07:00
|
|
|
// Promise Version
|
2016-05-03 14:06:32 +02:00
|
|
|
import { Injectable } from '@angular/core';
|
|
|
|
|
import { Http, Response } from '@angular/http';
|
|
|
|
|
import { Headers, RequestOptions } from '@angular/http';
|
|
|
|
|
import { Hero } from './hero';
|
2015-12-01 12:15:14 +01:00
|
|
|
|
|
|
|
|
@Injectable()
|
|
|
|
|
export class HeroService {
|
2016-02-17 18:13:57 +01:00
|
|
|
// URL to web api
|
2016-10-19 23:17:50 -07:00
|
|
|
private heroesUrl = 'app/heroes';
|
2015-12-01 12:15:14 +01:00
|
|
|
|
2016-06-08 01:06:25 +02:00
|
|
|
constructor (private http: Http) {}
|
|
|
|
|
|
2016-01-28 10:22:59 +01:00
|
|
|
// #docregion methods
|
2016-04-13 08:21:32 -07:00
|
|
|
getHeroes (): Promise<Hero[]> {
|
2016-05-03 14:06:32 +02:00
|
|
|
return this.http.get(this.heroesUrl)
|
2015-12-01 12:15:14 +01:00
|
|
|
.toPromise()
|
2016-04-13 08:21:32 -07:00
|
|
|
.then(this.extractData)
|
|
|
|
|
.catch(this.handleError);
|
2015-12-01 12:15:14 +01:00
|
|
|
}
|
|
|
|
|
|
2016-04-13 08:21:32 -07:00
|
|
|
addHero (name: string): Promise<Hero> {
|
2016-02-01 19:52:14 -08:00
|
|
|
let headers = new Headers({ 'Content-Type': 'application/json' });
|
|
|
|
|
let options = new RequestOptions({ headers: headers });
|
|
|
|
|
|
2016-10-19 23:17:50 -07:00
|
|
|
return this.http.post(this.heroesUrl, { name }, options)
|
2015-12-01 12:15:14 +01:00
|
|
|
.toPromise()
|
2016-04-13 08:21:32 -07:00
|
|
|
.then(this.extractData)
|
2016-01-28 10:22:59 +01:00
|
|
|
.catch(this.handleError);
|
2015-12-01 12:15:14 +01:00
|
|
|
}
|
2016-04-13 08:21:32 -07:00
|
|
|
|
|
|
|
|
private extractData(res: Response) {
|
|
|
|
|
let body = res.json();
|
|
|
|
|
return body.data || { };
|
|
|
|
|
}
|
|
|
|
|
|
2016-10-19 23:17:50 -07:00
|
|
|
private handleError (error: Response | any) {
|
2016-05-17 01:45:52 -07:00
|
|
|
// In a real world app, we might use a remote logging infrastructure
|
2016-10-19 23:17:50 -07:00
|
|
|
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);
|
2016-04-10 15:04:04 -07:00
|
|
|
return Promise.reject(errMsg);
|
2016-01-28 10:22:59 +01:00
|
|
|
}
|
2016-04-10 15:04:04 -07:00
|
|
|
|
2016-01-28 10:22:59 +01:00
|
|
|
// #enddocregion methods
|
2015-12-01 12:15:14 +01:00
|
|
|
}
|
|
|
|
|
// #enddocregion
|