25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

44 lines
1.3 KiB

  1. import { Injectable } from '@angular/core';
  2. import { Observable, Subject } from 'rxjs';
  3. import { filter } from 'rxjs/operators';
  4. import { Alert, AlertType, AlertOptions } from '@app/_models';
  5. @Injectable({ providedIn: 'root' })
  6. export class AlertService {
  7. private subject = new Subject<Alert>();
  8. private defaultId = 'default-alert';
  9. // enable subscribing to alerts observable
  10. onAlert(id = this.defaultId): Observable<Alert> {
  11. return this.subject.asObservable().pipe(filter(x => x && x.id === id));
  12. }
  13. // convenience methods
  14. success(message: string, options?: AlertOptions) {
  15. this.alert(new Alert({ ...options, type: AlertType.Success, message }));
  16. }
  17. error(message: string, options?: AlertOptions) {
  18. this.alert(new Alert({ ...options, type: AlertType.Error, message }));
  19. }
  20. info(message: string, options?: AlertOptions) {
  21. this.alert(new Alert({ ...options, type: AlertType.Info, message }));
  22. }
  23. warn(message: string, options?: AlertOptions) {
  24. this.alert(new Alert({ ...options, type: AlertType.Warning, message }));
  25. }
  26. // main alert method
  27. alert(alert: Alert) {
  28. alert.id = alert.id || this.defaultId;
  29. this.subject.next(alert);
  30. }
  31. // clear alerts
  32. clear(id = this.defaultId) {
  33. this.subject.next(new Alert({ id }));
  34. }
  35. }