我正在尝试为我的 ngrx 状态管理器实现 Effects。目前我正在使用 Angular v5.2.1
, ngrx v4.1.1
和 rxjs v5.5.6
.
例如,我尝试了“较旧”的方法
@Effect() login$: Observable<Action> = this.actions$.ofType('LOGIN')
.mergeMap(action =>
this.http.post('/auth', action.payload)
// If successful, dispatch success action with result
.map(data => ({ type: 'LOGIN_SUCCESS', payload: data }))
// If request fails, dispatch failed action
.catch(() => of({ type: 'LOGIN_FAILED' }))
);
但是我得到一个错误 Property 'mergeMap' does not exist on type 'Actions<Action>'
.
所以我用了新的pipe
方法。问题是当我尝试导入 ofType
运算符
// ...
import { Action } from '@ngrx/store';
import { Effect, Actions, ofType } from '@ngrx/effects';
import { map, mergeMap, catchError } from 'rxjs/operators';
import { of } from 'rxjs/observable/of';
@Injectable()
export class WifiEffects {
@Effect()
getWifiData: Observable<Action> = this.actions$.pipe(
ofType(WifiTypes.getWifiNetworks),
mergeMap((action: GetWifiNetworks) =>
this.mapService.getWifiNetworks().pipe(
map((data: WifiNetworks) => new GetWifiNetworksSucc(data)),
catchError(() => of(new GetWifiNetworksErr()))
)),
);
constructor (
private actions$: Actions,
private mapService: GoogleMapDataService
) {}
}
我遇到错误 Module '".../node_modules/@ngrx/effects/effects"' has no exported member 'ofType'.
有什么想法吗?
最佳答案
查看@ngrx/effects API , 没有迹象表明该库已经实现了 ofType
的可出租版本,因此您的第二个实现将不起作用(至少在管道内的 ofType
中不起作用)。
您的第一个实现只是缺少对 mergeMap
import 'rxjs/add/observable/mergeMap';
可能还有 map
和 catch
import 'rxjs/add/observable/map';
import 'rxjs/add/observable/catch';
如果你想将 ofType
与 pipe
一起使用,这可能会起作用
@Effect()
getWifiData: Observable<Action> =
this.actions$.ofType(WifiTypes.getWifiNetworks)
.pipe(
mergeMap((action: GetWifiNetworks) =>
...
因为 ofType()
返回一个已将 .pipe
添加到其原型(prototype)中的 Observable。
脚注
在查看 github 上的源代码后(截至 2018 年 1 月 22 日),我在此处找到了可出租 ofType
的导出 platform/modules/effects/src/index.ts .
但是在使用 @ngrx/effects@latest
安装时(它给了我 ver 4.1.1)我在安装的 node_modules 文件夹下看不到这个导出引用。
在我的组件中,我也不能使用 import { ofType } from '@ngrx/effects';
。
关于Angular 5 ngrx 效果没有导出成员 'ofType',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48368064/