HeroService returns an empty Observable, if the requested hero can't be found
[examples/angular-tour-of-heroes] / src / app / hero.service.ts
index 9003fe1..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';
@@ -19,6 +19,11 @@ export class HeroService {
 
   getHero(id: number): Observable<Hero> {
     this.messageService.add(`HeroService: fetched hero id=${id}`);
-    return of(HEROES.find(hero => hero.id === id));
+    const found: Hero | undefined = HEROES.find(hero => hero.id === id);
+    if (found === undefined) {
+      return EMPTY;
+    } else {
+      return of(found);
+    }
   }
 }