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

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

我在 Angular 中使用 redux 使用 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

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

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

在您的 index.ts 选择器代码中试试这个:

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