6: Get Data from a Server
[examples/angular-tour-of-heroes] / src / app / hero.service.ts
index 90fa42c..75a002b 100644 (file)
@@ -4,7 +4,7 @@ import { Hero } from './hero';
 import { HEROES } from './mock-heroes';
 import { HttpClient, HttpHeaders } from '@angular/common/http';
 import { MessageService } from './message.service';
-import { catchError } from 'rxjs/operators';
+import { catchError, tap } from 'rxjs/operators';
 
 
 @Injectable({
@@ -12,7 +12,7 @@ import { catchError } from 'rxjs/operators';
 })
 export class HeroService {
 
-  private heroesUrl = 'api/heroes';  // URL to web api
+  heroesUrl = 'api/heroes';  // URL to web api
 
   constructor(
     private http: HttpClient,
@@ -23,18 +23,19 @@ export class HeroService {
     return this.http
       .get<Hero[]>(this.heroesUrl)
       .pipe(
+        tap((heroes: Hero[]) => this.log(`fetched ${heroes.length} heroes`)),
         catchError(this.handleError<Hero[]>('getHeroes', []))
       );
   }
 
+  /** GET hero by id. Will 404 if id not found */
   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);
-    }
+    const url = `${this.heroesUrl}/${id}`;
+    return this.http.get<Hero>(url).pipe(
+      tap(_ => this.log(`fetched hero id=${id}`)),
+      catchError(this.handleError<Hero>(`getHero id=${id}`))
+    );
   }
 
   /**
@@ -53,7 +54,11 @@ export class HeroService {
       this.log(`${operation} failed: ${error.message}`);
 
       // Let the app keep running by returning an empty result.
-      return of(result as T);
+      if (result === undefined) {
+        return EMPTY as Observable<T>;
+      } else {
+        return of(result as T);
+      }
     };
   }