Skip to content

Instantly share code, notes, and snippets.

@bobbyg603
Last active May 13, 2022 13:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bobbyg603/c1deca84ba7436e8b89097dcd2211c65 to your computer and use it in GitHub Desktop.
Save bobbyg603/c1deca84ba7436e8b89097dcd2211c65 to your computer and use it in GitHub Desktop.
RxJS in the Wild: Alerts
import { HttpErrorResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { firstValueFrom, Observable, Subject, timer } from 'rxjs';
import { Alert, AlertColor } from './alert';
@Injectable({
providedIn: 'root',
})
export class AlertService {
private _state: Alert[] = [];
private _alertSubject = new Subject<Alert[]>();
private _alerts$?: Observable<Alert[]>;
get alerts$(): Observable<Alert[]> {
if (!this._alerts$) {
this._alerts$ = this._alertSubject.asObservable();
}
return this._alerts$;
}
dismissAlert(id: string): void {
this.removeAlert(id);
}
pushAlert(message: string, color: AlertColor = AlertColor.Red, autoDismiss: boolean = true): void {
const alert = new Alert(message, color, autoDismiss);
if (autoDismiss) {
firstValueFrom(
timer(5000)
).then(() => this.removeAlert(alert.id));
}
this.addAlert(alert);
}
private addAlert(alert: Alert): void {
this._state = this._state.concat(alert);
this._alertSubject.next(this._state);
}
private removeAlert(id: string): void {
this._state = this._state.filter(alert => alert.id !== id);
this._alertSubject.next(this._state)
}
}
import { v4 as uuid } from 'uuid';
export enum AlertColor {
Red,
Green,
Yellow
}
export class Alert {
readonly id = uuid();
constructor(
readonly message: string,
readonly color: AlertColor,
readonly autoDismiss: boolean = true
) { }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment