angular - 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个问题:
- 有谁知道我的代码错误是什么?
- 你知道为什么 withLatestFrom 返回 [never, Country[]],我认为 observable 应该更有帮助。
如果需要,我可以提供其他代码部分(减速器、动作......),但它非常接近我也用来学习 ngrx 的这个例子:https ://www.concretepage.com/angular-2/ngrx/ngrx-实体示例
非常感谢您的帮助 :)
解决方案
你错过了返回这里
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()..
,因为它是单行箭头函数。
推荐阅读
- intellij-idea - 是否可以清除 IntelliJ 剪贴板历史记录
- javascript - 字符串对象文件而不是实际对象
- reactjs - React Jest 测试:TestingLibraryElementError: Unable to find an element
- android - 无法从 recyclerview 实时数据库中删除项目
- python - 为什么递归python函数中没有更新函数参数?
- c - 为什么Arduino(Mega 2560)在端口监视器中显示少5个循环迭代结果?
- c++ - 如何将构造函数参数注入接口绑定?
- sprite - 尽管是精灵,但只能将精灵添加到组中
- c++ - 用于递归继承的具有类型和非类型参数混合的 C++ 可变参数模板
- r - R中构面图的颜色条宽度