Skip to content

Instantly share code, notes, and snippets.

@jagomf
Created June 20, 2018 10:40
Show Gist options
  • Save jagomf/b62e77ab2d72a752bf7d9657f78dc92f to your computer and use it in GitHub Desktop.
Save jagomf/b62e77ab2d72a752bf7d9657f78dc92f to your computer and use it in GitHub Desktop.
Angular: Communication using Subject in Services
import { Injectable } from '@angular/core';
import { Router, NavigationStart } from '@angular/router';
import { Observable } from 'rxjs';
import { Subject } from 'rxjs/Subject';
import { Alert, AlertType } from '../models/alert';
@Injectable()
export class AlertService {
private subject = new Subject<Alert>();
private keepAfterRouteChange = false;
constructor(private router: Router) {
router.events.subscribe(event => {
if (event instanceof NavigationStart) {
if (this.keepAfterRouteChange) {
this.keepAfterRouteChange = false;
} else {
this.clear();
}
}
});
}
getAlert(): Observable<any> {
return this.subject.asObservable();
}
success(message: string, keepAfterRouteChange = false) {
this.alert(AlertType.Success, message, keepAfterRouteChange);
}
error(message: string, keepAfterRouteChange = false) {
this.alert(AlertType.Error, message, keepAfterRouteChange);
}
info(message: string, keepAfterRouteChange = false) {
this.alert(AlertType.Info, message, keepAfterRouteChange);
}
warn(message: string, keepAfterRouteChange = false) {
this.alert(AlertType.Warning, message, keepAfterRouteChange);
}
alert(type: AlertType, message: string, keepAfterRouteChange = false) {
this.keepAfterRouteChange = keepAfterRouteChange;
this.subject.next(<Alert>{ type: type, message: message });
}
clear() {
this.subject.next();
}
}
...
this.alertService.success('Alert message);
...
import { Component, OnInit } from '@angular/core';
import { Alert, AlertType } from '../models/alert';
import { AlertService } from '../services/alert.service';
@Component({
selector: 'alert',
templateUrl: 'alert.component.html'
})
export class AlertComponent {
alerts: Alert[] = [];
constructor(private alertService: AlertService) {}
ngOnInit() {
this.alertService.getAlert().subscribe((alert: Alert) => {
if (!alert) {
this.alerts = [];
return;
}
this.alerts.push(alert);
});
}
removeAlert(alert: Alert) {
this.alerts = this.alerts.filter(x => x !== alert);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment