首页 > 解决方案 > 应用程序启动时未定义的 ngrx 状态,没有设置 StoreModule.forRoot()

问题描述

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

标签: angularundefinedngrxngrx-storengrx-effects

解决方案


你设置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


推荐阅读