Search code examples
angularngrxngrx-storeangular-module

How can we export shared Store, Actions, Reducers and Services to a different module? - Angular


Store, Actions, Reducers and some Services are in a separate shared module - suppose that module is shared.module.ts. If we want to use all these entities from a different module, how can we export it? I know we can export a component to other modules, but what about these? If I trigger an action from a different module, will it trigger a reducer in the shared module? Specific to Angular.


Solution

  • Your shared module:

    import { NgModule } from '@angular/core';
    import { RouterModule } from '@angular/router';
    import { EffectsModule } from '@ngrx/effects';
    import { RouterState, StoreRouterConnectingModule } from '@ngrx/router-store';
    import { StoreModule } from '@ngrx/store';
    import { StoreDevtoolsModule } from '@ngrx/store-devtools';
    
    import { environment } from 'src/environments/environment';
    import { reducers, metaReducers } from './app.state';  
    
    @NgModule({
        declarations: [],
        imports: [
            StoreModule.forRoot(reducers, { metaReducers }),
            RouterModule.forRoot([]),
            StoreRouterConnectingModule.forRoot({ routerState: RouterState.Minimal}),
            // Instrumentation must be imported after importing StoreModule (config is optional)
            StoreDevtoolsModule.instrument({
                maxAge: 25, // Retains last 25 states
                logOnly: environment.production, // Restrict extension to log-only mode
                autoPause: true, // Pauses recording actions and state changes when the extension window is not open
            }),
            EffectsModule.forRoot([
                // your effects here
            ]),
        ],
        exports: [
        ],
        providers: [],
        bootstrap: [],
        entryComponents: [],
    })
    export class SharedModule {}
    

    Then import it in another module:

    import { NgModule } from '@angular/core';
    
    import { SharedModule } from '../../shared/shared.module';
    
    @NgModule({
        declarations: [],
        imports: [SharedModule],
        exports: [],
        bootstrap: [],
    })
    export class CustomersModule {}