I have an Angular 7 application with a global @ngrx store (AppState) and a few feature stores (DashboardManagerState for example) that are lazy loaded with their corresponding module. The global store contains information about the logged in user such as id and a token for making http requests to our backend.
I have also created an interceptor to add the token to requests and a few other services use the agent id in their requests. Storing this information in Redux removes the need to constantly pass this information around or store it as a cookie.
While I've got this working I'm pretty sure I've gone about it in a hacky way and I'm looking to fix this.
I've got my application working by injecting the app state using this constructor in my token interceptor.
constructor(private store: Store<{ state: AppState }>) {}
I'm sure that is not correct. I've tried using selectors but the object coming in through that constructor has my stores as parameters and not the base store. It looks something like this
{
state: AppState,
dashboardManagerState: DashboardManagerState
}
so the selectors fail to properly run.
I've been able to add the global state onto my feature state but what class would I inject to my token interceptor? None are appropriate because this service must be global to the application.
Ideally I would be able to inject state as needed using Angular's DI so I could use the above constructor as constructor(private store: Store<AppState>) {}
and similarly when I want the feature state: constructor(private store: Store<DashboardManagerState>) {}
. I'm pretty sure that is not correct but I am unaware of the correct way to handle this sort of scenario.
How do I go about referencing my global state in a service that is injected into root?
First off, when you inject the Store
you will git the whole store. For example if you would do Store<DashboardManagerState>
, you will still get the whole store. The typing is only to make it typesafe in your component. In other words, at runtime it doesn't matter if you would do Store<{ state: AppState }>
or Store<DashboardManagerState>
.
I've tried using selectors but the object coming in through that constructor has my stores as parameters and not the base store
You probably have your selector written wrong?