angular-tour-of-heroes/src/app/hero-detail/hero-detail.component.ts

50 lines
1.1 KiB
TypeScript

import {Component, Input} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {Hero} from '../hero';
import {CommonModule} from '@angular/common';
import { ActivatedRoute } from '@angular/router';
import { HeroService } from '../hero.service';
import { Location } from '@angular/common';
@Component({
standalone: true,
selector: 'app-hero-detail',
templateUrl: './hero-detail.component.html',
styleUrls: ['./hero-detail.component.css'],
imports: [CommonModule, FormsModule]
})
export class HeroDetailComponent {
@Input() hero?: Hero;
constructor(
private route: ActivatedRoute,
private heroService: HeroService,
private location: Location
) {}
goBack(): void {
this.location.back();
}
ngOnInit(): void {
this.getHero();
}
getHero(): void {
const id = Number(this.route.snapshot.paramMap.get('id'));
this.heroService.getHero(id)
.subscribe(hero => this.hero = hero);
}
save(): void {
if (this.hero) {
this.heroService.updateHero(this.hero)
.subscribe(() => this.goBack());
}
}
}