HeroService returns an empty Observable, if the requested hero can't be found
[examples/angular-tour-of-heroes] / src / app / hero.service.ts
index 7e0771a..1db6072 100644 (file)
@@ -1,6 +1,8 @@
 import { Injectable } from '@angular/core';
+import { Observable, of, EMPTY } from 'rxjs';
 import { Hero } from './hero';
 import { HEROES } from './mock-heroes';
+import { MessageService } from './message.service';
 
 
 @Injectable({
@@ -8,9 +10,20 @@ import { HEROES } from './mock-heroes';
 })
 export class HeroService {
 
-  constructor() { }
+  constructor(private messageService : MessageService) { }
 
-  getHeroes() : Hero[] {
-    return HEROES;
+  getHeroes() : Observable<Hero[]> {
+    this.messageService.add('HeroService: fetching heroes...');
+    return of(HEROES);
+  }
+
+  getHero(id: number): Observable<Hero> {
+    this.messageService.add(`HeroService: fetched hero id=${id}`);
+    const found: Hero | undefined = HEROES.find(hero => hero.id === id);
+    if (found === undefined) {
+      return EMPTY;
+    } else {
+      return of(found);
+    }
   }
 }