Ngrx angular 2 How to set the initial state?

I am using angular 2 and Ngrx.

I have an application for the main component in which I subscribe to the name of the application in the NgOnInit function. And I have a child component Home, where I send this title also to NgOnInit, because I want to change the title when the user visits the home component.

The problem is that my App component is the parent of the Home component, and it is called first, so in my subscription I end up with an undefined object that should contain a header.

What is the best solution for this? I can set the initial title in the constructor (it is called first) I can get the name in the subscription as follows: (store || {}).title Or is there any way to set the initial state in the reducer?

+5
source share
1 answer

Ultimately, if the value is simply displayed in the template, you can always use the async pipe:

 <h1>{{ (someReducer | async)?.title }}</h1> 

Alternatively, you can set the initial state inside the gearbox itself:

 function someReducer (state = {title: 'Home'}, action) { switch (action.type) { default: return state; } } 

Finally, you can set the initial state when the store is initialized:

 StoreModule.provideStore(reducers, initialState) 

Hope this helps you in some way.

Tom

+7
source

Source: https://habr.com/ru/post/1264360/


All Articles