From f18faff7c576b595dd8765f36805aa8176122db7 Mon Sep 17 00:00:00 2001 From: Kai Moritz Date: Sat, 9 May 2020 01:57:09 +0200 Subject: [PATCH] 5: Add In-app Navigation e) Routable HeroDetailComponent --- .../hero-detail/hero-detail.component.html | 1 + src/app/hero-detail/hero-detail.component.ts | 19 ++++++++++++++++++- src/app/hero.service.ts | 5 +++++ 3 files changed, 24 insertions(+), 1 deletion(-) diff --git a/src/app/hero-detail/hero-detail.component.html b/src/app/hero-detail/hero-detail.component.html index fa00c62..512825a 100644 --- a/src/app/hero-detail/hero-detail.component.html +++ b/src/app/hero-detail/hero-detail.component.html @@ -6,3 +6,4 @@ + diff --git a/src/app/hero-detail/hero-detail.component.ts b/src/app/hero-detail/hero-detail.component.ts index caa9c09..c252bcf 100644 --- a/src/app/hero-detail/hero-detail.component.ts +++ b/src/app/hero-detail/hero-detail.component.ts @@ -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(); + } } diff --git a/src/app/hero.service.ts b/src/app/hero.service.ts index 8df8f33..9003fe1 100644 --- a/src/app/hero.service.ts +++ b/src/app/hero.service.ts @@ -16,4 +16,9 @@ export class HeroService { this.messageService.add('HeroService: fetching heroes...'); return of(HEROES); } + + getHero(id: number): Observable { + this.messageService.add(`HeroService: fetched hero id=${id}`); + return of(HEROES.find(hero => hero.id === id)); + } } -- 2.20.1