]> juplo.de Git - examples/angular-tour-of-heroes/commitdiff
5: Add In-app Navigation
authorKai Moritz <kai@juplo.de>
Fri, 8 May 2020 23:57:09 +0000 (01:57 +0200)
committerKai Moritz <kai@juplo.de>
Mon, 11 May 2020 16:23:16 +0000 (18:23 +0200)
e) Routable HeroDetailComponent

src/app/hero-detail/hero-detail.component.html
src/app/hero-detail/hero-detail.component.ts
src/app/hero.service.ts

index fa00c62aff6156302c358d40dc9592d79f4226c1..512825aea806ce6d16ee613a081c8a30a6d840ad 100644 (file)
@@ -6,3 +6,4 @@
     <input [(ngModel)]="hero.name" placeholder="Type a name..." />
   </div>
 </div>
+<button (click)="goBack()">go back</button>
index caa9c091e162601ab48c8c6d150e1aa7c2ac6aa4..c252bcffe4905eb339cd4ecbd01d71c7690a29f6 100644 (file)
@@ -1,4 +1,8 @@
 import { Component, OnInit, Input } from '@angular/core';
+import { ActivatedRoute } from '@angular/router';
+import { Location } from '@angular/common';
+
+import { HeroService } from '../hero.service';
 import { Hero } from '../hero';
 
 @Component({
@@ -10,9 +14,22 @@ export class HeroDetailComponent implements OnInit {
 
   @Input() hero : Hero;
 
-  constructor() { }
+  constructor(
+    private route: ActivatedRoute,
+    private heroService: HeroService,
+    private location: Location
+  ) { }
 
   ngOnInit() {
+    this.getHero();
+  }
+
+  getHero(): void {
+    const id = +this.route.snapshot.paramMap.get('id');
+    this.heroService.getHero(id).subscribe(hero => this.hero = hero);
   }
 
+  goBack(): void {
+    this.location.back();
+  }
 }
index 8df8f33af31d49fc5afa8f07ffe10b12a05e8b70..9003fe1fb02718907bde31a3bfc4eb3bac35c734 100644 (file)
@@ -16,4 +16,9 @@ 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}`);
+    return of(HEROES.find(hero => hero.id === id));
+  }
 }