Hero in HeroDetailComponent can be undefined: resetting prior to fetching
[examples/angular-tour-of-heroes] / src / app / hero-detail / hero-detail.component.ts
index caa9c09..4bbfe2e 100644 (file)
@@ -1,4 +1,8 @@
-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';
 
 @Component({
@@ -8,11 +12,27 @@ import { Hero } from '../hero';
 })
 export class HeroDetailComponent implements OnInit {
 
-  @Input() hero : Hero;
+  hero: Hero | undefined;
 
-  constructor() { }
+  constructor(
+    private route: ActivatedRoute,
+    private heroService: HeroService,
+    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.hero = hero);
+    });
   }
 
+  goBack(): void {
+    this.location.back();
+  }
 }