应用启动时未定义的ngrx状态,未设置StoreModule.forRoot()

时间:2018-07-03 07:58:15

标签: angular undefined ngrx ngrx-store ngrx-effects

我正在使用redux在Angular中使用ngrx,但是最初我得到undefined的值是为什么

这是我的代码不要在chrome上运行(在chrome浏览器中出现在stackblitz中)请使用其他浏览器。

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
  }
);

我正在打印我给我undefined的状态。请帮助。检查元素并查看错误

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

2 个答案:

答案 0 :(得分:2)

您错误地设置了NgRx。在AppModule中,必须使用StoreModule.forRoot(...)。在功能模块中,您将使用StoreModule.forFeature(...) 为了使您的示例正常工作,我在此处进行了修复: https://stackblitz.com/edit/angular-8tuwu8?file=src/app/index.ts

在此处查看示例应用:https://github.com/ngrx/platform/tree/master/example-app

答案 1 :(得分:-1)

您要创建的featureSelector商店中未加载任何功能模块(代码中没有StoreModule.forFeature('products', reducer)

在index.ts选择器代码中尝试以下操作:

export const getProducts = (state: fromProduct.ProductState) => state.products;