6: Get Data from a Server
[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, tap } from 'rxjs/operators';
8
9
10 @Injectable({
11   providedIn: 'root'
12 })
13 export class HeroService {
14
15   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         tap((heroes: Hero[]) => this.log(`fetched ${heroes.length} heroes`)),
27         catchError(this.handleError<Hero[]>('getHeroes', []))
28       );
29   }
30
31   /** GET hero by id. Will 404 if id not found */
32   getHero(id: number): Observable<Hero> {
33     this.log(`requested hero id=${id}`);
34     const url = `${this.heroesUrl}/${id}`;
35     return this.http.get<Hero>(url).pipe(
36       tap(_ => this.log(`fetched hero id=${id}`)),
37       catchError(this.handleError<Hero>(`getHero id=${id}`))
38     );
39   }
40
41   /**
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
46    */
47   private handleError<T>(operation = 'operation', result?: T) {
48     return (error: any): Observable<T> => {
49
50       // TODO: send the error to remote logging infrastructure
51       console.error(error); // log to console instead
52
53       // TODO: better job of transforming error for user consumption
54       this.log(`${operation} failed: ${error.message}`);
55
56       // Let the app keep running by returning an empty result.
57       if (result === undefined) {
58         return EMPTY as Observable<T>;
59       } else {
60         return of(result as T);
61       }
62     };
63   }
64
65   /** Log a HeroService message with the MessageService */
66   private log(message: string) {
67     this.messageService.add(`HeroService: ${message}`);
68   }
69 }