90fa42c4eafc17eea7cebd39385df345a8e7e3ff
[examples/angular-tour-of-heroes] / src / app / hero.service.ts
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 } from 'rxjs/operators';
8
9
10 @Injectable({
11   providedIn: 'root'
12 })
13 export class HeroService {
14
15   private heroesUrl = 'api/heroes';  // URL to web api
16
17   constructor(
18     private http: HttpClient,
19     private messageService: MessageService) { }
20
21   getHeroes(): Observable<Hero[]> {
22     this.log('fetching heroes...');
23     return this.http
24       .get<Hero[]>(this.heroesUrl)
25       .pipe(
26         catchError(this.handleError<Hero[]>('getHeroes', []))
27       );
28   }
29
30   getHero(id: number): Observable<Hero> {
31     this.log(`requested hero id=${id}`);
32     const found: Hero | undefined = HEROES.find(hero => hero.id === id);
33     if (found === undefined) {
34       return EMPTY;
35     } else {
36       return of(found);
37     }
38   }
39
40   /**
41    * Handle Http operation that failed.
42    * Let the app continue.
43    * @param operation - name of the operation that failed
44    * @param result - optional value to return as the observable result
45    */
46   private handleError<T>(operation = 'operation', result?: T) {
47     return (error: any): Observable<T> => {
48
49       // TODO: send the error to remote logging infrastructure
50       console.error(error); // log to console instead
51
52       // TODO: better job of transforming error for user consumption
53       this.log(`${operation} failed: ${error.message}`);
54
55       // Let the app keep running by returning an empty result.
56       return of(result as T);
57     };
58   }
59
60   /** Log a HeroService message with the MessageService */
61   private log(message: string) {
62     this.messageService.add(`HeroService: ${message}`);
63   }
64 }