angular-tour-of-heroes/src/app/heroes/heroes.component.ts
2022-09-30 11:30:08 +02:00

37 lines
949 B
TypeScript

import { Component, OnInit } from '@angular/core';
import { Hero } from '../hero';
import { HeroService } from '../hero.service';
import { MessageService } from '../messages.service';
@Component({
selector: 'app-heroes',
templateUrl: './heroes.component.html',
styleUrls: ['./heroes.component.scss']
})
export class HeroesComponent implements OnInit {
constructor(private heroService: HeroService, private messageService: MessageService) { }
heroes: Hero[] = []
ngOnInit(): void {
this.getHeroes()
}
getHeroes(): void {
this.heroService.getHeroes().subscribe(heroes => this.heroes = heroes)
}
add(name: string): void {
name = name.trim()
if (!name) { return }
this.heroService.addHero({ name } as Hero).subscribe((hero: Hero) => {this.heroes.push(hero)})
}
delete(hero: Hero): void {
this.heroes = this.heroes.filter(h => h !== hero)
this.heroService.deleteHero(hero.id).subscribe()
}
}