首页 > 解决方案 > Ngrx 效果:无法从商店或服务中获取实体

问题描述

我正在使用ngrx(商店,效果,实体,storedevtools)开发一个角度8应用程序。我也在发现ngrx。我按照官方文档中的教程进行操作,一切正常,直到我决定优化我的应用程序的 http 请求。

如果实体已经加载并且如果没有联系我的服务,我想对商店进行检查。

我用谷歌搜索并找到了这个例子,然后受到了启发,但我有一个问题 https://medium.com/@haldun7/caching-http-requests-while-using-ngrx-effects-98abd50c5c78

我来自控制台浏览器的问题是:

错误类型错误:“您在预期流的位置提供了‘未定义’。您可以提供 Observable、Promise、Array 或 Iterable。”

这是出现问题的效果:

  @Effect() 
  loadAllCountries$ = this.actions$.pipe(
    ofType(fromActions.CountryActionTypes.LOAD_ALL_COUNTRIES),
    withLatestFrom(this.store.pipe(select(fromReducers.selectAllCountries))),
    switchMap((list) => { // <= this guy is a [never, Country[]] object and I don't know why :(
      if (list[1].length !== 0) {

        var temp = list[1];

        return [new fromActions.LoadCountriesSuccess( {countries: temp })];
      }
      this.service.getCountries().pipe(
        map(data => new fromActions.LoadCountriesSuccess({ countries: data })))
    })
  );

这很奇怪,因为在逐步调试时,list[1] 等于 0,所以 else 部分应该毫无问题地执行。

这是效果的非优化版本,运行良好

  @Effect() 
  loadAllCountries$: Observable<Action> = this.actions$.pipe(
    ofType(fromActions.CountryActionTypes.LOAD_ALL_COUNTRIES),
    switchMap(() => 
         this.service.getCountries().pipe(
         map(data => new fromActions.LoadCountriesSuccess({ countries: data })) 
      )));

基本上我有2个问题:

  1. 有谁知道我的代码错误是什么?
  2. 你知道为什么 withLatestFrom 返回 [never, Country[]],我认为 observable 应该更有帮助。

如果需要,我可以提供其他代码部分(减速器、动作......),但它非常接近我也用来学习 ngrx 的这个例子:https ://www.concretepage.com/angular-2/ngrx/ngrx-实体示例

非常感谢您的帮助 :)

标签: angularngrx

解决方案


你错过了返回这里

return this.service.getCountries().pipe(
        map(data => new fromActions.LoadCountriesSuccess({ countries: data }))). 

因此,您的 switchMap 不会返回任何内容。在这种情况下

switchMap(() => 
         this.service.getCountries().pipe(
         map(data => new fromActions.LoadCountriesSuccess({ countries: data })) 
      )))

您的代码会自动返回结果this.service.getCountries()..,因为它是单行箭头函数。


推荐阅读