I am using angular 2 and Ngrx.
I have main component App where I am subscribing to app title in NgOnInit function And I have child component Home where I am dispatching this title also in NgOnInit cause I want to change title when user visit home component.
The problem is that my App component is parent of Home component, and it is called first, so in my subscribe I end up with undefined object which should contain title.
What is the best solution for this?
I can set initial title in constructor (it is called first)
I can get title in subscribe like this: (store || {}).title
Or is any way to set initial state in reducer?
Ultimately, if the value is just output in the template, you could always use the async
pipe:
<h1>{{ (someReducer | async)?.title }}</h1>
Alternatively you could set some initial state inside the reducer itself:
function someReducer (state = {title: 'Home'}, action) {
switch (action.type) {
default:
return state;
}
}
Finally, you can set initial state when the store is initialised:
StoreModule.provideStore(reducers, initialState)
Hopefully this helps you in some way.
Tom
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With