/
component-communication-event.service.ts
42 lines (36 loc) · 1.39 KB
/
component-communication-event.service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import { Subject, Subscription } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ComponentCommunicationEventService {
// create a subject to hold data which can be subscribed to.
// you only get the data after you subscribe.
private _subject$ = new Subject();
// used in the listening component.
// i.e. this.componentCommunicationEventService = this._componentCommunicationEventService.on(Events.loginSuccess, () => doSomething());
on(event: Events, action: () => void): Subscription {
return this._subject$
.pipe(
// filter down based on event name to any events that are emitted out of the subject from the emit method below.
filter((e: EmitEvent) => e.name === event),
map((e: EmitEvent) => e.value)
)
.subscribe(action); // subscribe to the subject to get the data.
}
// used in the emitting component.
// i.e. this.componentCommunicationEventService.emit(new EmitEvent(Events.loginSuccess));
emit(event: EmitEvent) {
this._subject$.next(event);
}
}
export class EmitEvent {
constructor(public name: any, public value?: any) { }
}
// possible events that can be emitted.
export enum Events {
loginSuccess,
gravSearchExecuted,
projectCreated
}