forked from angular/angular.io
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhero-detail.component.ts
60 lines (54 loc) · 1.58 KB
/
hero-detail.component.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// #docplaster
// #docregion, variables-imports
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
// #enddocregion variables-imports
import { RouteParams } from '@angular/router-deprecated';
import { Hero } from './hero';
import { HeroService } from './hero.service';
@Component({
selector: 'my-hero-detail',
templateUrl: 'app/hero-detail.component.html',
styleUrls: ['app/hero-detail.component.css']
})
// #docregion variables-imports
export class HeroDetailComponent implements OnInit {
@Input() hero: Hero;
@Output() close = new EventEmitter();
error: any;
navigated = false; // true if navigated here
// #enddocregion variables-imports
constructor(
private heroService: HeroService,
private routeParams: RouteParams) {
}
// #docregion ngOnInit
ngOnInit() {
if (this.routeParams.get('id') !== null) {
let id = +this.routeParams.get('id');
this.navigated = true;
this.heroService.getHero(id)
.then(hero => this.hero = hero);
} else {
this.navigated = false;
this.hero = new Hero();
}
}
// #enddocregion ngOnInit
// #docregion save
save() {
this.heroService
.save(this.hero)
.then(hero => {
this.hero = hero; // saved hero, w/ id if new
this.goBack(hero);
})
.catch(error => this.error = error); // TODO: Display error message
}
// #enddocregion save
// #docregion goBack
goBack(savedHero: Hero = null) {
this.close.emit(savedHero);
if (this.navigated) { window.history.back(); }
}
// #enddocregion goBack
}