HeroDetailComponent issues a message after successfull retrival of a hero
[examples/angular-tour-of-heroes] / src / app / hero-detail / hero-detail.component.ts
index caa9c09..76e7912 100644 (file)
@@ -1,5 +1,10 @@
-import { Component, OnInit, Input } from '@angular/core';
+import { Component, OnInit } from '@angular/core';
+import { ActivatedRoute } from '@angular/router';
+import { Location } from '@angular/common';
+
+import { HeroService } from '../hero.service';
 import { Hero } from '../hero';
+import { MessageService } from '../message.service';
 
 @Component({
   selector: 'app-hero-detail',
@@ -8,11 +13,31 @@ import { Hero } from '../hero';
 })
 export class HeroDetailComponent implements OnInit {
 
-  @Input() hero : Hero;
+  hero: Hero | undefined;
 
-  constructor() { }
+  constructor(
+    private route: ActivatedRoute,
+    private heroService: HeroService,
+    private messageService: MessageService,
+    private location: Location
+  ) { }
 
   ngOnInit() {
+    this.getHero();
+  }
+
+  getHero(): void {
+    this.route.params.subscribe(params => {
+      const id: number = +params.id;
+      this.hero = undefined;
+      this.heroService.getHero(id).subscribe(hero => {
+        this.messageService.add('HeroDetailComponent: retrived hero ' + JSON.stringify(hero));
+        this.hero = hero;
+      });
+    });
   }
 
+  goBack(): void {
+    this.location.back();
+  }
 }