Creating Nested slices with NgRx store following the lazy modules structure

1k Views Asked by At

I am new to NgRx. In my project We have 3 levels of lazy Modules. I want the store's state to be nested according to the modules hierarchy but when I am writing: storeModule.forFeature('child',reducer) I am getting a flat slice of state instead of hierarchical one.

For example if I have parent module and a child module. I will define at the parent Module storeModule.forFeature('father',reducer) and in the child module storeModure.forFeature('child',reducer)

the result of the state will not be

{ father { child {}}}

rather it will be:

{ father {}, child {}}

Is there a way to make the state hierarchical as the way the lazy modules are?

1

There are 1 best solutions below

0
On

You actually can have lazy loaded state slices. Imagine you have the following module configuration

app
  father
    child

And you want (as you described) to have the following state

{
  father: {
    child: {}
  }
}

You need to ensure that:

  • You have a router in the AppModule and a Router in the FatherModule.
  • You lazy load the FatherModule in the AppModules router(!).
  • You lazy load the ChildModule in the FatherModules router(!).
  • The configuration in the imports is correct: In the ChildModule: StoreModule.forFeature('child', childreducers) and in the FatherModule: StoreModule.forFeature('father', fatherreducers).

For example if you navigate to a component in the FatherModule it'll load the father feature. But not necessarily the child feature. Only if you navigate to some subroute which loads the ChildModule.

What you currently do is having both forFeature methods in the same module. That does not make any sense because the "feature" is directly related to the module.