import { Injectable, Inject, NgModule } from '@angular/core';
import { NgxsPlugin, NGXS_PLUGINS } from '@ngxs/store';
export const NGXS_LOGGER_PLUGIN_OPTIONS = new InjectionToken('NGXS_LOGGER_PLUGIN_OPTIONS');
@Injectable()
export class LoggerPlugin implements NgxsPlugin {
constructor(@Inject(NGXS_LOGGER_PLUGIN_OPTIONS) private options: any) {}
handle(state, action, next) {
console.log('Action started!', state);
return next(state, action).pipe(
tap(result => {
console.log('Action happened!', result);
})
);
}
}
@NgModule()
export class NgxsLoggerPluginModule {
static forRoot(config?: any): ModuleWithProviders {
return {
ngModule: NgxsLoggerPluginModule,
providers: [
{
provide: NGXS_PLUGINS,
useClass: LoggerPlugin,
multi: true
},
{
provide: NGXS_LOGGER_PLUGIN_OPTIONS,
useValue: config
}
]
};
}
}
export function logPlugin(state, action, next) {
console.log('Action started!', state);
return next(state, action).pipe(tap(result) => {
console.log('Action happened!', result);
});
}
@NgModule({
imports: [NgxsModule.forRoot([ZooStore]), NgxsLoggerPluginModule.forRoot({})]
})
export class MyModule {}