angular-cn/public/docs/_examples/router/ts/app/crisis-center/crisis-detail.component.ts
2016-06-16 13:24:49 -07:00

99 lines
2.5 KiB
TypeScript

// #docplaster
// #docregion
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromPromise';
import { Crisis, CrisisService } from './crisis.service';
import { DialogService } from '../dialog.service';
@Component({
template: `
<div *ngIf="crisis">
<h3>"{{editName}}"</h3>
<div>
<label>Id: </label>{{crisis.id}}</div>
<div>
<label>Name: </label>
<input [(ngModel)]="editName" placeholder="name"/>
</div>
<p>
<button (click)="save()">Save</button>
<button (click)="cancel()">Cancel</button>
</p>
</div>
`,
styles: ['input {width: 20em}']
})
export class CrisisDetailComponent implements OnInit, OnDestroy {
crisis: Crisis;
editName: string;
private sub: any;
constructor(
private service: CrisisService,
private route: ActivatedRoute,
private router: Router,
private dialogService: DialogService
) { }
ngOnInit() {
this.sub = this.route
.params
.subscribe(params => {
let id = +params['id'];
this.service.getCrisis(id)
.then(crisis => {
if (crisis) {
this.editName = crisis.name;
this.crisis = crisis;
} else { // id not found
this.gotoCrises();
}
});
});
}
ngOnDestroy() {
if (this.sub) {
this.sub.unsubscribe();
}
}
cancel() {
this.gotoCrises();
}
save() {
this.crisis.name = this.editName;
this.gotoCrises();
}
canDeactivate(): Observable<boolean> | boolean {
// Allow synchronous navigation (`true`) if no crisis or the crisis is unchanged
if (!this.crisis || this.crisis.name === this.editName) {
return true;
}
// Otherwise ask the user with the dialog service and return its
// promise which resolves to true or false when the user decides
let p = this.dialogService.confirm('Discard changes?');
let o = Observable.fromPromise(p);
return o;
}
// #docregion gotoCrises
gotoCrises() {
let crisisId = this.crisis ? this.crisis.id : null;
// Pass along the hero id if available
// so that the CrisisListComponent can select that hero.
// Add a totally useless `foo` parameter for kicks.
// #docregion gotoCrises-navigate
// Absolute link
this.router.navigate(['/crisis-center', {id: crisisId, foo: 'foo'}]);
// #enddocregion gotoCrises-navigate
}
// #enddocregion gotoCrises
}