1 import { Injectable } from '@angular/core';
2 import { Observable, of, EMPTY } from 'rxjs';
3 import { Hero } from './hero';
4 import { HEROES } from './mock-heroes';
5 import { HttpClient, HttpHeaders } from '@angular/common/http';
6 import { MessageService } from './message.service';
7 import { catchError, tap } from 'rxjs/operators';
13 export class HeroService {
15 private heroesUrl = 'api/heroes'; // URL to web api
18 private http: HttpClient,
19 private messageService: MessageService) { }
21 getHeroes(): Observable<Hero[]> {
22 this.log('fetching heroes...');
24 .get<Hero[]>(this.heroesUrl)
26 tap((heroes: Hero[]) => this.log(`fetched ${heroes.length} heroes`)),
27 catchError(this.handleError<Hero[]>('getHeroes', []))
31 getHero(id: number): Observable<Hero> {
32 this.log(`requested hero id=${id}`);
33 const found: Hero | undefined = HEROES.find(hero => hero.id === id);
34 if (found === undefined) {
42 * Handle Http operation that failed.
43 * Let the app continue.
44 * @param operation - name of the operation that failed
45 * @param result - optional value to return as the observable result
47 private handleError<T>(operation = 'operation', result?: T) {
48 return (error: any): Observable<T> => {
50 // TODO: send the error to remote logging infrastructure
51 console.error(error); // log to console instead
53 // TODO: better job of transforming error for user consumption
54 this.log(`${operation} failed: ${error.message}`);
56 // Let the app keep running by returning an empty result.
57 return of(result as T);
61 /** Log a HeroService message with the MessageService */
62 private log(message: string) {
63 this.messageService.add(`HeroService: ${message}`);