Created
May 20, 2021 13:09
-
-
Save rafaeldcastro/b8545badee46973b9f570c5fc8fd2179 to your computer and use it in GitHub Desktop.
Not an "angular" way to handle notifications/subscribes, but come in handy.
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 { 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