Last active
May 13, 2022 13:26
-
-
Save bobbyg603/c1deca84ba7436e8b89097dcd2211c65 to your computer and use it in GitHub Desktop.
RxJS in the Wild: Alerts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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