import { Component , OnDestroy , OnInit } from '@angular/core' ; import { ActivatedRoute , Router } from '@angular/router' ; import { Subscription } from 'rxjs' ; import { finalize } from 'rxjs/operators' ; import { MessageService , Villain } from '../../core' ; import { VILLAIN_DETAIL_CONTAINER } from '../villain-detail-container' ; import { VillainService } from '../villain.service' ; @ Component ( { selector : 'aw-villains' , templateUrl : './villains.component.html' , styleUrls : [ './villains.component.scss' ] } ) export class VillainsComponent implements OnInit , OnDestroy { private subscription : Subscription ; selectedVillain : Villain ; villains : Villain [ ] ; constructor ( private villainService , private router , private route , private messageService ) { } ngOnInit ( ) { this . listenToViewDetailContainer ( ) ; this . getVillains ( ) ; } ngOnDestroy ( ) { this . subscription . unsubscribe ( ) ; } clear ( ) { this . selectedVillain = null ; } enableAddMode ( ) { this . selectedVillain = < any > { } ; this . router . navigate ( [ 'details' , 0 ] , { relativeTo : this . route } ) ; } getVillains ( ) { this . clear ( ) ; this . villainService . getVillains ( ) . subscribe ( villains => ( this . villains = villains ) ) ; } onSelect ( villain ) { this . selectedVillain = villain ; this . router . navigate ( [ 'details' , villain . id ] , { relativeTo : this . route } ) ; } add ( villain ) { this . villainService . addVillain ( villain ) . subscribe ( addedVillain => ( this . villains = this . villains . concat ( addedVillain ) ) ) ; } deleteVillain ( villain ) { this . clear ( ) ; this . villainService . deleteVillain ( villain ) . subscribe ( ( ) => ( this . villains = this . villains . filter ( h => h . id !== villain . id ) ) ) ; } update ( villain ) { this . villainService . updateVillain ( villain ) . subscribe ( ( ) => ( this . villains = this . villains . map ( h => ( h . id === villain . id ? villain : h ) ) ) ) ; } private listenToViewDetailContainer ( ) { this . subscription = this . messageService . listen$ . subscribe ( ( { message , sender } ) => { if ( sender === VILLAIN_DETAIL_CONTAINER ) { if ( message . match ( /add|update/i ) ) { this . getVillains ( ) ; } else if ( message . match ( /close/i ) ) { this . router . navigate ( [ './' ] , { relativeTo : this . route } ) ; this . clear ( ) ; } } } ) ; } }