Skip to content

Instantly share code, notes, and snippets.

@rafaeldcastro
Created May 20, 2021 13:09
Show Gist options
  • Save rafaeldcastro/b8545badee46973b9f570c5fc8fd2179 to your computer and use it in GitHub Desktop.
Save rafaeldcastro/b8545badee46973b9f570c5fc8fd2179 to your computer and use it in GitHub Desktop.
Not an "angular" way to handle notifications/subscribes, but come in handy.
import { Injectable } from '@angular/core';
import { EventEmitter } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class EventEmitterService {
private static emitters: { [notificationName: string]: EventEmitter<any> } = {}
static get(notificationName: string): EventEmitter<any>{
if (!this.emitters[notificationName])
this.emitters[notificationName] = new EventEmitter<any>();
return this.emitters[notificationName];
}
}
/**
to SUBSCRIBE:
private subscriptions = new Subscription();
constructor(){
this.subscriptions.add( EventEmitterService.get("notification_name").subscribe(payload => this.notificationHandler(payload)) );
}
TO EMIT:
EventEmitterService.get("notification_name").emit(payload);
to UNSUBSCRIBE:
ngOnDestroy(){
this.subscriptions.unsubscribe();
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment