使用 ngrx 中的选择器进行 http 调用和获取数据

Making http call and fetching data using selectors in ngrx

我是 ngrx 的新手,正试图在我的应用程序中实现存储。我遇到了一种情况,比如在我的页面加载时,我正在发出一个 http 请求并尝试从选择器中获取数据。由于 http 是异步的,而且我立即调用了引发错误的选择器方法。

触发负载调度程序的 PFB 组件代码,我期待 this.products$

中的结果
  ngOnInit() {

    this.store.dispatch(new productActions.Load());
    this.products$ = this.store.pipe(select(fromProducts.getProducts));
    that.initForms();
  }

我的效果

  @Effect()
    loadProducts$: Observable<Action> = this.actions$.pipe(
      ofType(productActions.productActionTypes.Load),
      mergeMap(action =>
        this.productService.getProductData().pipe(
          map(products=> (new productActions.LoadSuccess(products))),
          catchError(err => of(new productActions.LoadFail(err)))
        )
      )
    );

选择器

export const getProducts = createSelector(
    getProductFeatureState,
    state => state.products
);

我得到的错误是由上述选择器方法触发的

ERROR TypeError: Cannot read property 'products' of undefined

有办法解决这个问题吗?请分享您对此的看法

蒂亚

设置一个空的初始状态解决了这个问题