common-ui/src/lib/services/toaster.service.ts
2021-08-23 12:54:13 +03:00

86 lines
3.2 KiB
TypeScript

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 } 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 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?: { readonly title?: string; readonly action: () => void }[];
}
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<ErrorToasterOptions>): ActiveToast<unknown> {
let resultedMsg;
if (options?.error) 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<ToasterOptions>): ActiveToast<unknown> {
return this._showToastNotification(message, NotificationType.INFO, options);
}
success(message: string, options?: Partial<ToasterOptions>): ActiveToast<unknown> {
return this._showToastNotification(message, NotificationType.SUCCESS, options);
}
warning(message: string, options?: Partial<ToasterOptions>): ActiveToast<unknown> {
return this._showToastNotification(message, NotificationType.WARNING, options);
}
private _showToastNotification(
message: string,
notificationType = NotificationType.INFO,
options?: Partial<ToasterOptions>
): ActiveToast<unknown> {
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);
}
}
}