Skip to content

Instantly share code, notes, and snippets.

@denisemauldin
Created February 12, 2018 20:13
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 denisemauldin/5d16236a8784c6895162ede25f3573b0 to your computer and use it in GitHub Desktop.
Save denisemauldin/5d16236a8784c6895162ede25f3573b0 to your computer and use it in GitHub Desktop.
export class Alert {
readonly message: string;
readonly type: 'success' | 'error' | 'secondary' | 'warning' | 'alert';
readonly timeout: number;
constructor(message: string,
type: 'success' | 'error' | 'secondary' | 'warning' | 'alert',
timeout?: number) {
this.message = message;
this.type = type;
this.timeout = timeout || 10000;
}
equal(alert: Alert): boolean {
return this.message == alert.message && this.type == alert.type && this.timeout == alert.timeout;
}
}
<div class="row">
<alert *ngFor="let alert of alerts | async" [alert]="alert" (closed)="remove(alert)"></alert>
</div>
import { Component, OnInit } from "@angular/core";
import { ReplaySubject } from "rxjs/ReplaySubject";
import { Alert } from "./alert";
import { AlertsService } from "./alerts.service";
@Component({
moduleId: module.id,
selector: 'alerts',
templateUrl: 'alerts.component.html'
})
export class AlertsComponent implements OnInit {
private alerts: ReplaySubject<Array<Alert>>;
constructor(private service: AlertsService) { }
remove(alert: Alert) {
this.service.remove(alert);
}
ngOnInit(): void {
this.alerts = this.service.observable();
}
}
import { Router } from '@angular/router';
import { Injectable } from '@angular/core';
import { ReplaySubject } from 'rxjs/ReplaySubject';
import { Alert } from './alert';
@Injectable()
export class AlertsService {
private alerts: Array<Alert> = [];
private alertsSubject = new ReplaySubject<Array<Alert>>();
constructor(router: Router) {
router.events.subscribe(() => this.clean());
}
observable(): ReplaySubject<Array<Alert>> {
return this.alertsSubject;
}
error(message: string, timeout?: number) {
this.add(new Alert(message, 'error', timeout));
}
success(message: string, timeout?: number) {
this.add(new Alert(message, 'success', timeout));
}
warning(message: string, timeout?: number) {
this.add(new Alert(message, 'warning', timeout));
}
secondary(message: string, timeout?: number) {
this.add(new Alert(message, 'secondary', timeout));
}
alert(message: string, timeout?: number) {
this.add(new Alert(message, 'alert', timeout));
}
remove(alert: Alert) {
this.alerts = this.alerts.filter((item: Alert) => !alert.equal(item));
this.next();
}
clean() {
this.alerts.length = 0;
this.next();
}
private next() {
this.alertsSubject.next(this.alerts);
document.body.scrollTop = 0;
}
private add(alert: Alert) {
this.alerts = this.alerts.filter((item: Alert) => !alert.equal(item));
this.alerts.unshift(alert);
this.next();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment