|
| 1 | +// #docplaster |
| 2 | +// #docregion |
| 3 | +import 'rxjs/add/operator/map'; |
| 4 | +import 'rxjs/add/operator/delay'; |
| 5 | +import 'rxjs/add/operator/catch'; |
| 6 | +import { Injectable } from '@angular/core'; |
| 7 | +import { Http, Response, Headers } from '@angular/http'; |
| 8 | +import { Observable } from 'rxjs/Observable'; |
| 9 | + |
| 10 | +import { Hero } from './hero'; |
| 11 | +import { ApiError, ApiErrorHandlerService } from './api-error-handler.service'; |
| 12 | + |
| 13 | +@Injectable() |
| 14 | +export class HeroService { |
| 15 | + private headers = new Headers({'Content-Type': 'application/json'}); |
| 16 | + private heroesUrl = 'api/heroes'; |
| 17 | + |
| 18 | + constructor( |
| 19 | + private http: Http, |
| 20 | + private errorHandler: ApiErrorHandlerService |
| 21 | + ) {} |
| 22 | + |
| 23 | + addHero(hero: Hero) { |
| 24 | + return this.http.post(this.heroesUrl, JSON.stringify({ name: hero.name }), { headers: this.headers }); |
| 25 | + } |
| 26 | + |
| 27 | + getHeroes(): Observable<Hero[]> { |
| 28 | + return this.http.get(this.heroesUrl) |
| 29 | + .map(response => response.json().data as Hero[]); |
| 30 | + } |
| 31 | + |
| 32 | + getFailedHeroes(): Observable<any> { |
| 33 | + return this.http.get(`${this.heroesUrl}/failed`) |
| 34 | + } |
| 35 | + |
| 36 | + getHero(id: number): Observable<Hero> { |
| 37 | + const url = `${this.heroesUrl}/${id}`; |
| 38 | + return this.http.get(url) |
| 39 | + .map(response => response.json().data as Hero); |
| 40 | + } |
| 41 | + |
| 42 | + search(term: string): Observable<Hero[]> { |
| 43 | + return this.http |
| 44 | + .get(`${this.heroesUrl}/?name=${term}`) |
| 45 | + .map((r: Response) => r.json().data as Hero[]); |
| 46 | + } |
| 47 | +} |
0 commit comments