11// #docplaster
22// #docregion, variables-imports
3- import { Component , EventEmitter , Input , OnInit , Output } from '@angular/core' ;
3+ import { Component , EventEmitter , Input , OnInit , OnDestroy , Output } from '@angular/core' ;
44
55// #enddocregion variables-imports
6- import { RouteParams } from '@angular/router-deprecated ' ;
6+ import { ActivatedRoute } from '@angular/router' ;
77
88import { Hero } from './hero' ;
99import { HeroService } from './hero.service' ;
@@ -14,31 +14,39 @@ import { HeroService } from './hero.service';
1414 styleUrls : [ 'app/hero-detail.component.css' ]
1515} )
1616// #docregion variables-imports
17- export class HeroDetailComponent implements OnInit {
17+ export class HeroDetailComponent implements OnInit , OnDestroy {
1818 @Input ( ) hero : Hero ;
1919 @Output ( ) close = new EventEmitter ( ) ;
2020 error : any ;
21+ sub : any ;
2122 navigated = false ; // true if navigated here
2223 // #enddocregion variables-imports
2324
2425 constructor (
2526 private heroService : HeroService ,
26- private routeParams : RouteParams ) {
27+ private route : ActivatedRoute ) {
2728 }
2829
2930 // #docregion ngOnInit
3031 ngOnInit ( ) {
31- if ( this . routeParams . get ( 'id' ) !== null ) {
32- let id = + this . routeParams . get ( 'id' ) ;
33- this . navigated = true ;
34- this . heroService . getHero ( id )
35- . then ( hero => this . hero = hero ) ;
36- } else {
37- this . navigated = false ;
38- this . hero = new Hero ( ) ;
39- }
32+ this . sub = this . route . params . subscribe ( params => {
33+ if ( params [ 'id' ] !== undefined ) {
34+ let id = + params [ 'id' ] ;
35+ this . navigated = true ;
36+ this . heroService . getHero ( id )
37+ . then ( hero => this . hero = hero ) ;
38+ } else {
39+ this . navigated = false ;
40+ this . hero = new Hero ( ) ;
41+ }
42+ } ) ;
4043 }
4144 // #enddocregion ngOnInit
45+
46+ ngOnDestroy ( ) {
47+ this . sub . unsubscribe ( ) ;
48+ }
49+
4250 // #docregion save
4351 save ( ) {
4452 this . heroService
@@ -57,4 +65,3 @@ export class HeroDetailComponent implements OnInit {
5765 }
5866 // #enddocregion goBack
5967}
60-
0 commit comments