alert_srv.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. import angular from 'angular';
  2. import _ from 'lodash';
  3. import coreModule from 'app/core/core_module';
  4. import appEvents from 'app/core/app_events';
  5. export class AlertSrv {
  6. list: any[];
  7. /** @ngInject */
  8. constructor(private $timeout, private $rootScope) {
  9. this.list = [];
  10. }
  11. init() {
  12. this.$rootScope.onAppEvent(
  13. 'alert-error',
  14. (e, alert) => {
  15. this.set(alert[0], alert[1], 'error', 12000);
  16. },
  17. this.$rootScope
  18. );
  19. this.$rootScope.onAppEvent(
  20. 'alert-warning',
  21. (e, alert) => {
  22. this.set(alert[0], alert[1], 'warning', 5000);
  23. },
  24. this.$rootScope
  25. );
  26. this.$rootScope.onAppEvent(
  27. 'alert-success',
  28. (e, alert) => {
  29. this.set(alert[0], alert[1], 'success', 3000);
  30. },
  31. this.$rootScope
  32. );
  33. appEvents.on('alert-warning', options => this.set(options[0], options[1], 'warning', 5000));
  34. appEvents.on('alert-success', options => this.set(options[0], options[1], 'success', 3000));
  35. appEvents.on('alert-error', options => this.set(options[0], options[1], 'error', 7000));
  36. }
  37. getIconForSeverity(severity) {
  38. switch (severity) {
  39. case 'success':
  40. return 'fa fa-check';
  41. case 'error':
  42. return 'fa fa-exclamation-triangle';
  43. default:
  44. return 'fa fa-exclamation';
  45. }
  46. }
  47. set(title, text, severity, timeout) {
  48. if (_.isObject(text)) {
  49. console.log('alert error', text);
  50. if (text.statusText) {
  51. text = `HTTP Error (${text.status}) ${text.statusText}`;
  52. }
  53. }
  54. var newAlert = {
  55. title: title || '',
  56. text: text || '',
  57. severity: severity || 'info',
  58. icon: this.getIconForSeverity(severity),
  59. };
  60. var newAlertJson = angular.toJson(newAlert);
  61. // remove same alert if it already exists
  62. _.remove(this.list, function(value) {
  63. return angular.toJson(value) === newAlertJson;
  64. });
  65. this.list.push(newAlert);
  66. if (timeout > 0) {
  67. this.$timeout(() => {
  68. this.list = _.without(this.list, newAlert);
  69. }, timeout);
  70. }
  71. if (!this.$rootScope.$$phase) {
  72. this.$rootScope.$digest();
  73. }
  74. return newAlert;
  75. }
  76. clear(alert) {
  77. this.list = _.without(this.list, alert);
  78. }
  79. clearAll() {
  80. this.list = [];
  81. }
  82. }
  83. coreModule.service('alertSrv', AlertSrv);