cyb*_*ast 6 ngrx ngrx-effects angular ngrx-store-4.0
如何在效果中访问我的状态?我当前的效果实现(如下所示)是在SEARCH_REUQUEST分派动作时触发的。但是,在调用我的搜索服务以启动 HTTP 请求之前,我想访问一个状态以获取一些搜索参数。
@Effect()
SearchRequest$ = this.actions$
.ofType(fromSearchActions.SearchActionTypes.SEARCH_REQUEST)
.pipe(
switchMap((action: fromSearchActions.SearchRequest) => {
return this.searchService
.search(action.payload, action.enrichmentId)
.pipe(
map(response => {
console.group("SEARCH effects");
console.log(response);
console.groupEnd();
return new fromSearchActions.SearchRequestSuccess(response);
}),
catchError(error =>
of(new fromSearchActions.SearchRequestFail(error))
)
);
})
);
Run Code Online (Sandbox Code Playgroud)
显然,我可以在这里利用一个 RxJS 运算符,但我似乎无法理解如何修改现有的效果实现以合并它。
@Effect()
SearchRequest$ = this.actions$
.ofType(fromSearchActions.SearchActionTypes.SEARCH_REQUEST)
.withLatestFrom(this.featureStore.select(fromFeature.getCurrentSearchPageOptions))
.pipe(
switchMap((// How should this change? //) => { //Error
return this.searchService
.search(action.payload, action.enrichmentId, pageOptions)
.pipe(
map(response => {
console.group("SEARCH effects");
console.log(response);
console.groupEnd();
return new fromSearchActions.SearchRequestSuccess(response);
}),
catchError(error =>
of(new fromSearchActions.SearchRequestFail(error))
)
);
})
)
Run Code Online (Sandbox Code Playgroud)
我觉得我已经接近解决方案了,但我似乎无法在switchMap舞台上把它放在一起。
withLatestFrom:将源 Observable 与其他 Observable 组合起来创建一个 Observable,其值是根据每个 Observable 的最新值计算得出的。
您将得到一个包含这两个数据的数组,您可以在https://medium.com/@viestursv/how-to-get-store-state-in-ngrx-effect-fab9e9c8f087中找到指南
你的代码可能是这样的:
@Effect()
SearchRequest$ = this.actions.pipe(
ofType(fromSearchActions.SearchActionTypes.SEARCH_REQUEST),
withLatestFrom(this.featureStore.select(fromFeature.getCurrentSearchPageOptions)),
switchMap(([action: Action, pageOptions: YourStateOptions]) => { // <-- pageOptions here
return this.searchService
.search(action.payload, action.enrichmentId, pageOptions)
.pipe(
map(response => {
console.group("SEARCH effects");
console.log(response);
console.groupEnd();
return new fromSearchActions.SearchRequestSuccess(response);
}),
catchError(error =>
of(new fromSearchActions.SearchRequestFail(error))
)
);
}
)
);
Run Code Online (Sandbox Code Playgroud)
withLatestFrom 绝对是你想要的。您所要做的就是将响应添加到您在 switchMap 中传递的参数。像这样(其中 pageOptions 是从选择器获得的状态切片的类型):
switchMap(([action, options]: [fromSearchActions.SearchRequest, pageOptions]) => {
Run Code Online (Sandbox Code Playgroud)
然后你可以action像以前一样使用,这options将是你从中得到的结果this.featureStore.select(fromFeature.getCurrentSearchPageOptions)
| 归档时间: |
|
| 查看次数: |
4462 次 |
| 最近记录: |