If several Angular standalone components depend on the same feature module, what is the way to make that feature module shared, i.e. loaded and initialized only once?
In my case, to avoid loading unnecessary state upfront, I bundle my NgRx features into Angular modules:
import { NgModule } from "@angular/core";
import { StoreModule } from "@ngrx/store";
import { EffectsModule } from "@ngrx/effects";
...
@NgModule({ imports: [
StoreModule.forFeature(MY_FEATURE_KEY, myFeatureReducer),
EffectsModule.forFeature(myFeatureEffects)
]})
export class MyNgrxFeatureModule {
constructor(store: Store) {
console.log('MyNgrxFeatureModule initializing');
store.dispatch(initializeData());
}
}
where some data initialization initializeData()
(usually involving a network call to a data backend) is triggered during Module initialization.
Some Angular standalone components import the NgRx feature module:
@Component({
selector: 'app-goods-table',
standalone: true,
imports: [ MyNgrxFeatureModule, ... ],
...
})
export class MyComponent1 {
// ...
}
I observe that each component importing the MyNgrxFeatureModule
seems to re-initialize the feature module (the console.log()
in the feature module constructor is executed repeatedly, apparently once for each standalone component chunk loaded).
What is the way to lazy-load (or initialize) shared feature modules once, when multiple stand-alone components depend on them? (I am using the latest Angular 17 and NgRx 17?)
One way is to lift state up so it's only registered once.
On the other hand, it shouldn't be a problem to register state multiple times. NgRx will detect it's already registered and will "ignore" it. E.g. effects won't get registered twice, and the state won't be overwritten.