5

I am using Angular 7 with Ngrx and Rxjs 6. I got 2 lazy loaded modules A and B which have their own selectors and reducers.

Now, I would like to access the data stored on the module B state from the module A. The problem is that all of the ngrx components of module B get initialized only when the user navigates to the lazy loaded route of B, so if the user first goes to A , attempting to select the state will result in undefined errors because B is not yet initialized.

What would be the best practice in accessing the state of a lazy loaded module in this case?

qubits
  • 1,227
  • 3
  • 20
  • 50
  • 4
    By design, its a bad practice to depend on lazy loaded modules. Why not create a store at the root level which is always present in the browser. – Amit Chigadani May 18 '19 at 14:36
  • I would agree with @AmitChigadani, if the state is being used by multiple modules then probably belongs in a parent state. Especially if one of those modules is being lazy loaded. – JCherryhomes May 18 '19 at 22:18
  • I agree as well. The reducers should all be initialized at the root, whether as part of a lazy loaded module or not. – Tzannetos Philippakos May 20 '19 at 11:51
  • 2
    While I might decide to move the reducers as recommended myself since the request is anyway not made until the select so it doesn't seem to punish performance, I still wonder then why is there a StoreModule.forFeature import in Ngrx then? What would be the use case? @JCherryhomes. In most of the applications the state will always be shared between feature modules eventually – qubits May 20 '19 at 14:20
  • @PiotrJerzyMamenas I would say that depends. If you have a modules that have restricted access it would also make sense that there would be state that would only be available to those modules. The main issue here though is that if the state is loaded as part of a lazy loaded module it is simply not available before that module loads because it doesn't exist yet. I think the options here are either to not lazy load that module or move the state to a shared module that will be loaded and available. – JCherryhomes May 20 '19 at 14:31

1 Answers1

4

In my opinion his use case is valid and ngrx ought to be able to handle it but it drops state if a reducer is not added to ngrx through the forFeature function because a lazy loaded module is not yet loaded which makes it impossible to retrieve the entire state from a database in the backend and use it as needed in lazy loaded modules.