Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ngrx angular 2 How should I set initial state?

Tags:

angular

ngrx

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?

like image 591
gkucmierz Avatar asked Feb 17 '17 18:02

gkucmierz


1 Answers

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

like image 65
Thomas Maddocks Avatar answered Nov 04 '22 07:11

Thomas Maddocks