6: Get Data from a Server
[examples/angular-tour-of-heroes] / src / app / hero.service.ts
index 7e0771a..d44f22f 100644 (file)
@@ -1,6 +1,9 @@
 import { Injectable } from '@angular/core';
+import { Observable, of, EMPTY } from 'rxjs';
 import { Hero } from './hero';
 import { HEROES } from './mock-heroes';
+import { HttpClient } from '@angular/common/http';
+import { MessageService } from './message.service';
 
 
 @Injectable({
@@ -8,9 +11,29 @@ import { HEROES } from './mock-heroes';
 })
 export class HeroService {
 
-  constructor() { }
+  private heroesUrl = 'api/heroes';  // URL to web api
 
-  getHeroes() : Hero[] {
-    return HEROES;
+  constructor(
+    private http: HttpClient,
+    private messageService: MessageService) { }
+
+  getHeroes(): Observable<Hero[]> {
+    this.log('fetching heroes...');
+    return this.http.get<Hero[]>(this.heroesUrl);
+  }
+
+  getHero(id: number): Observable<Hero> {
+    this.log(`requested hero id=${id}`);
+    const found: Hero | undefined = HEROES.find(hero => hero.id === id);
+    if (found === undefined) {
+      return EMPTY;
+    } else {
+      return of(found);
+    }
+  }
+
+  /** Log a HeroService message with the MessageService */
+  private log(message: string) {
+    this.messageService.add(`HeroService: ${message}`);
   }
 }