import { Injectable } from '@angular/core' ; import { Router , NavigationStart } from '@angular/router' ; import { Observable } from 'rxjs' ; import { Subject } from 'rxjs/Subject' ; import 'rxjs/add/operator/filter' ; import { Alert , AlertType } from '../_models/alert' ; @ Injectable ( ) export class AlertService { private subject = new Subject < Alert > ( ) ; private keepAfterRouteChange = false ; constructor ( private router ) { router . events . subscribe ( event => { if ( event instanceof NavigationStart ) { if ( this . keepAfterRouteChange ) { this . keepAfterRouteChange = false ; } else { this . clear ( ) ; } } } ) ; } getAlert ( alertId ? ) { return this . subject . asObservable ( ) . filter ( ( x ) => x && x . alertId === alertId ) ; } success ( message ) { this . alert ( new Alert ( { message , type : AlertType . Success } ) ) ; } error ( message ) { this . alert ( new Alert ( { message , type : AlertType . Error } ) ) ; } info ( message ) { this . alert ( new Alert ( { message , type : AlertType . Info } ) ) ; } warn ( message ) { this . alert ( new Alert ( { message , type : AlertType . Warning } ) ) ; } alert ( alert ) { this . keepAfterRouteChange = alert . keepAfterRouteChange ; this . subject . next ( alert ) ; } clear ( alertId ? ) { this . subject . next ( new Alert ( { alertId } ) ) ; } }