All files / src/app/services alert.service.ts

100% Statements 16/16
100% Branches 5/5
100% Functions 4/4
100% Lines 14/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 621x 1x 1x           1x   167x   167x               167x 20686x 5168x   2x     5166x                       7x 7x                                   40x      
import { Injectable } from '@angular/core';
import { NavigationStart, Router } from '@angular/router';
import { Observable, Subject } from 'rxjs';
 
/**
 * Alert Service
 */
@Injectable()
export class AlertService {
    /** collection of messages */
    private readonly subject = new Subject<any>();
    /** do you want to keep message as shown even after gone to another page? */
    private keepAfterNavigationChange = false;
 
    /**
     * constructor of AlertService
     * @param router: Router
     */
    constructor(router: Router) {
        // clear alert message on route change
        router.events.subscribe(event => {
            if (event instanceof NavigationStart) {
                if (this.keepAfterNavigationChange) {
                    // only keep for a single location change
                    this.keepAfterNavigationChange = false;
                } else {
                    // clear alert
                    this.subject.next();
                }
            }
        });
    }
 
    /**
     * Show message to user
     * @param message: message text
     * @param keepAfterNavigationChange: do you want to keep message as shown even after gone to another page?
     */
    success(message: string, keepAfterNavigationChange = false): void {
        this.keepAfterNavigationChange = keepAfterNavigationChange;
        this.subject.next({type: 'success', text: message});
    }
 
    // istanbul ignore next
    /**
     * Show error to user
     * @param message: error text
     * @param keepAfterNavigationChange: do you want to keep message as shown even after gone to another page?
     */
    error(message: string, keepAfterNavigationChange = false): void {
        this.keepAfterNavigationChange = keepAfterNavigationChange;
        this.subject.next({type: 'error', text: message});
    }
 
    /**
     * get current messages
     */
    getMessage(): Observable<any> {
        return this.subject.asObservable();
    }
}