Issue
We have a situatuin where we have a root module with corresponding root store and multiple feature modules with their own featuee stores.
We have a need for different feature modules to dispatch root store actions and thus update state in root store.
I know each feature state can access root state but I am wondering if there is a way to do that inter-module communication differently?
What I would like to avoie is to have direct dependency on root module.
So, is there any other mechanism to exchange info between modules?
PS. Modules are lazy loaded.
Solution
Create a service with providedIn: root
(do not import this service anywhere!), use the variables to communicate between modules, if you need to call method, you need to use an EventBus using Subject on a service (not by me!)
We can subscribe listeners and emit events from two components that are in different modules, as long as they are in the same angular application, you can communicate freely using this method!
If you give providedIn 'root', the service will automatically be provided in the root of angular application, no need for imports!
import { Injectable } from '@angular/core';
import { Subject, Subscription } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { ConsoleData } from './ConsoleData';
@Injectable({
providedIn: 'root',
})
export class EventBusService {
sharedVariable = '';
private subject$ = new Subject();
emit(event: ConsoleData) {
this.subject$.next(event);
}
on(event: string, action: any): Subscription {
return this.subject$
.pipe(
filter((e: ConsoleData) => e.name == event),
map((e: ConsoleData) => e.value)
)
.subscribe(action);
}
constructor() {}
}
Although the provided stackblitz is not lazy loaded, the concept applies the same,
Answered By - Naren Murali
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.