import { Component , OnInit } from '@angular/core' ; import { finalize } from 'rxjs/operators' ; import { Villain } from '../../core' ; import { VillainService } from '../villain.service' ; @ Component ( { selector : 'aw-villains' , templateUrl : './villains.component.html' , styleUrls : [ './villains.component.scss' ] } ) export class VillainsComponent implements OnInit { selectedVillain : Villain ; villains : Villain [ ] ; loading : boolean ; constructor ( private villainService ) { } ngOnInit ( ) { this . getVillains ( ) ; } clear ( ) { this . selectedVillain = null ; } deleteVillain ( villain ) { this . loading = true ; this . unselect ( ) ; this . villainService . deleteVillain ( villain ) . pipe ( finalize ( ( ) => ( this . loading = false ) ) ) . subscribe ( ( ) => ( this . villains = this . villains . filter ( h => h . id !== villain . id ) ) ) ; } enableAddMode ( ) { this . selectedVillain = < any > { } ; } getVillains ( ) { this . loading = true ; this . villainService . getVillains ( ) . pipe ( finalize ( ( ) => ( this . loading = false ) ) ) . subscribe ( villains => ( this . villains = villains ) ) ; this . unselect ( ) ; } onSelect ( villain ) { this . selectedVillain = villain ; } update ( villain ) { this . loading = true ; this . villainService . updateVillain ( villain ) . pipe ( finalize ( ( ) => ( this . loading = false ) ) ) . subscribe ( ( ) => ( this . villains = this . villains . map ( h => ( h . id === villain . id ? villain : h ) ) ) ) ; } add ( villain ) { this . loading = true ; this . villainService . addVillain ( villain ) . pipe ( finalize ( ( ) => ( this . loading = false ) ) ) . subscribe ( addedvillain => ( this . villains = this . villains . concat ( addedvillain ) ) ) ; } unselect ( ) { this . selectedVillain = null ; } }