import { Injectable } from '@angular/core'; import { ActiveToast, ToastrService } from 'ngx-toastr'; import { IndividualConfig } from 'ngx-toastr/toastr/toastr-config'; import { NavigationStart, Router } from '@angular/router'; import { TranslateService } from '@ngx-translate/core'; import { HttpErrorResponse, HttpStatusCode } from '@angular/common/http'; import { filter } from 'rxjs/operators'; import { ErrorMessageService } from './error-message.service'; const enum NotificationType { SUCCESS = 'SUCCESS', WARNING = 'WARNING', INFO = 'INFO', } export interface ToasterActions { readonly title?: string; readonly action: () => void; } export interface ToasterOptions extends IndividualConfig { readonly title?: string; /** * These params are used as interpolateParams for translate service */ // eslint-disable-next-line @typescript-eslint/ban-types readonly params?: object; readonly actions?: ToasterActions[]; } export interface ErrorToasterOptions extends ToasterOptions { /** * Pass an http error that will be processed by error message service and shown in toast */ readonly error?: HttpErrorResponse; } @Injectable({ providedIn: 'root', }) export class Toaster { constructor( private readonly _toastr: ToastrService, private readonly _router: Router, private readonly _translateService: TranslateService, private readonly _errorMessageService: ErrorMessageService, ) { _router.events.pipe(filter(event => event instanceof NavigationStart)).subscribe(() => { _toastr.clear(); }); } error(message: string, options?: Partial): ActiveToast { let resultedMsg; if (options?.error && options.error.status !== HttpStatusCode.Conflict) { resultedMsg = this._errorMessageService.getMessage(options.error, message); } else { resultedMsg = this._translateService.instant(message, options?.params) as string; } return this._toastr.error(resultedMsg, options?.title, options); } info(message: string, options?: Partial): ActiveToast { return this._showToastNotification(message, NotificationType.INFO, options); } success(message: string, options?: Partial): ActiveToast { return this._showToastNotification(message, NotificationType.SUCCESS, options); } warning(message: string, options?: Partial): ActiveToast { return this._showToastNotification(message, NotificationType.WARNING, options); } private _showToastNotification( message: string, notificationType = NotificationType.INFO, options?: Partial, ): ActiveToast { const translatedMsg = this._translateService.instant(message, options?.params) as string; switch (notificationType) { case NotificationType.SUCCESS: return this._toastr.success(translatedMsg, options?.title, options); case NotificationType.WARNING: return this._toastr.warning(translatedMsg, options?.title, options); case NotificationType.INFO: default: return this._toastr.info(translatedMsg, options?.title, options); } } }