1
0
mirror of https://github.com/xuthus83/pigallery2.git synced 2024-11-03 21:04:03 +08:00
pigallery2/frontend/app/model/notification.service.ts

81 lines
2.3 KiB
TypeScript
Raw Normal View History

2018-03-31 03:30:30 +08:00
import {Injectable, ViewContainerRef} from '@angular/core';
import {ToastsManager} from 'ng2-toastr/ng2-toastr';
import {NetworkService} from './network/network.service';
import {AuthenticationService} from './network/authentication.service';
import {NotificationDTO, NotificationType} from '../../../common/entities/NotificationDTO';
import {UserDTO, UserRoles} from '../../../common/entities/UserDTO';
import {I18n} from '@ngx-translate/i18n-polyfill';
2017-07-08 18:43:42 +08:00
@Injectable()
export class NotificationService {
options = {
2018-03-31 03:30:30 +08:00
positionClass: 'toast-top-center',
animate: 'flyLeft'
2017-07-08 18:43:42 +08:00
};
2017-07-09 20:23:50 +08:00
notifications: NotificationDTO[] = [];
lastUser: UserDTO = null;
2017-07-08 18:43:42 +08:00
2017-07-09 20:23:50 +08:00
constructor(private _toastr: ToastsManager,
private _networkService: NetworkService,
2018-03-30 08:30:23 +08:00
private _authService: AuthenticationService,
public i18n: I18n) {
2017-07-08 18:43:42 +08:00
2017-07-09 20:23:50 +08:00
this._authService.user.subscribe(() => {
if (this._authService.isAuthenticated() &&
(!this.lastUser ||
2018-02-04 08:50:42 +08:00
this.lastUser.id != this._authService.user.value.id) &&
this._authService.user.value.role >= UserRoles.Guest) {
2017-07-09 20:23:50 +08:00
this.getServerNotifications();
}
this.lastUser = this._authService.user.value;
});
}
async getServerNotifications() {
2018-03-31 03:30:30 +08:00
this.notifications = await this._networkService.getJson<NotificationDTO[]>('/notifications');
2017-07-09 20:23:50 +08:00
this.notifications.forEach((noti) => {
let msg = noti.message;
if (noti.details) {
2018-03-31 03:30:30 +08:00
msg += ' Details: ' + JSON.stringify(noti.details);
2017-07-09 20:23:50 +08:00
}
switch (noti.type) {
case NotificationType.error:
2018-03-31 03:30:30 +08:00
this.error(msg, this.i18n('Server error'));
2017-07-09 20:23:50 +08:00
break;
case NotificationType.warning:
2018-03-31 03:30:30 +08:00
this.warning(msg, this.i18n('Server error'));
2017-07-09 20:23:50 +08:00
break;
case NotificationType.info:
2018-03-31 03:30:30 +08:00
this.info(msg, this.i18n('Server info'));
2017-07-09 20:23:50 +08:00
break;
}
2018-03-31 03:30:30 +08:00
});
2017-07-08 18:43:42 +08:00
}
setRootViewContainerRef(vcr: ViewContainerRef) {
this._toastr.setRootViewContainerRef(vcr);
}
success(text, title = null) {
this._toastr.success(text, title, this.options);
}
error(text, title?) {
this._toastr.error(text, title, this.options);
}
warning(text, title?) {
this._toastr.warning(text, title, this.options);
}
info(text, title = null) {
this._toastr.info(text, title, this.options);
}
get Toastr(): ToastsManager {
return this._toastr;
}
}