Skip to content

17. Event Aggregator

Ali Badakhshan edited this page Jun 29, 2019 · 4 revisions

Narik Event Aggregator

Since Narik is a module framework, you sometimes need to handle events from one module in another module. Narik Event Aggregator Service helps you to do that easily.

/**
* Event aggregator service
* A service that manage events inside application.
*/
export abstract class EventAggregatorService {

 /**
  * Publish event aggregator service
  * @param eventType eventType
  * @param eventArgs  event argument
  */
 abstract publish(eventType: any, eventArgs: any);

 /**
  * Listens event aggregator service
  * @param eventType  eventType
  * @returns  an `Observable` that emit whenever event occurs.
  */
 abstract  listen<T>(eventType: any): Observable<T>;
}

It has two methods. One for listen and another for publishing. For example, you may listen for "MODULE_LOAD_COMPLETELY" event to do something when one module loads completely.

example:

export class ModuleLoadCompletelyGuard implements CanActivate {
  constructor(
     private eventAggregatorService: EventAggregatorService
  ) {}

  canActivate(route: ActivatedRouteSnapshot) {
    const moduleKey = route.data["moduleKey"];
    return Observable.create((observer: Observer<any>) => {
      this.eventAggregatorService
        .listen<{ moduleKey: string }>("MODULE_LOAD_COMPLETELY")
        .pipe(
          filter(x => x.moduleKey === moduleKey),
          first()
        )
        .subscribe(() => {
          observer.next(true);
        });
    });
  }
}

Each event can be published by its owner. For example "MODULE_LOAD_COMPLETELY" is published by ModuleManager.

export class test
{
    someMethod()
    {
        this.eventAggregatorService.publish("MODULE_LOAD_COMPLETELY", {
            moduleKey: key,
            moduleInfo: moduleInfo
        });
    }
}

Narik Event Aggregator Service use one subject for each event type. If you specify event's attributes in metadata, Event Aggregator Service uses them, otherwise uses simple subject.

Events Metadata