Search code examples
angularundefinedngrxngrx-storengrx-effects

undefined ngrx state on app start, no StoreModule.forRoot() set up


I am using redux in Angular using ngrx .but i am getting undefined value initially why

here is my code don't run this on chrome (issue in stackblitz in chrome browser ) Please use other browser.

https://stackblitz.com/edit/angular-sz7rul?file=src%2Fapp%2Findex.ts

const getProductFeatureState =createFeatureSelector<fromProduct.ProductState>('productFeature')

export const getProducts = createSelector(
  getProductFeatureState,
  state => {

    console.log(state);
    return state.products
  }
);

I am printing my state it is giving me undefined .please help .Inspect the element and see the error

preview-fe7237b13d780dbf847da.js:1 ERROR TypeError: Cannot read property 'products' of undefined
    at eval (VM2486 index.ts:15)
    at eval (selector.js:84)
    at memoized (selector.js:34)
    at defaultStateFn (selector.js:58)
    at eval (selector.js:87)
    at MapSubscriber.memoized [as project] (selector.js:34)
    at MapSubscriber._next (map.ts:78)
    at MapSubscriber.Subscriber.next (Subscriber.ts:102)
    at State.BehaviorSubject._subscribe (BehaviorSubject.ts:24)
    at State.Observable._trySubscribe

Solution

  • You're setting up the NgRx wrongly. In the AppModule, use have to use StoreModule.forRoot(...). In the feature module, you will use StoreModule.forFeature(...) For your example to work, I fixed it here: https://stackblitz.com/edit/angular-8tuwu8?file=src/app/index.ts

    See example app here: https://github.com/ngrx/platform/tree/master/example-app