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 } from '@angular/common/http';
6 import { MessageService } from './message.service';
7
8
9 @Injectable({
10   providedIn: 'root'
11 })
12 export class HeroService {
13
14   private heroesUrl = 'api/heroes';  // URL to web api
15
16   constructor(
17     private http: HttpClient,
18     private messageService: MessageService) { }
19
20   getHeroes(): Observable<Hero[]> {
21     this.log('fetching heroes...');
22     return this.http.get<Hero[]>(this.heroesUrl);
23   }
24
25   getHero(id: number): Observable<Hero> {
26     this.log(`requested hero id=${id}`);
27     const found: Hero | undefined = HEROES.find(hero => hero.id === id);
28     if (found === undefined) {
29       return EMPTY;
30     } else {
31       return of(found);
32     }
33   }
34
35   /** Log a HeroService message with the MessageService */
36   private log(message: string) {
37     this.messageService.add(`HeroService: ${message}`);
38   }
39 }