HeroService returns an empty Observable, if the requested hero can't be found
[examples/angular-tour-of-heroes] / src / app / hero.service.ts
index 8df8f33..1db6072 100644 (file)
@@ -1,5 +1,5 @@
 import { Injectable } from '@angular/core';
-import { Observable, of } from 'rxjs';
+import { Observable, of, EMPTY } from 'rxjs';
 import { Hero } from './hero';
 import { HEROES } from './mock-heroes';
 import { MessageService } from './message.service';
@@ -16,4 +16,14 @@ export class HeroService {
     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);
+    }
+  }
 }