如何访问效果中的部分状态?调度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))
)
);
})
);
显然,这里有一个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))
)
);
})
)
我觉得我已经接近解决方案,但是我似乎无法在switchmap阶段将其放在一起。
答案 0 :(得分:1)
withLatestFrom绝对是您想要的。您要做的就是将响应添加到在switchMap中传递的参数。像这样(其中pageOptions是从选择器获得的状态切片的类型):
switchMap(([action, options]: [fromSearchActions.SearchRequest, pageOptions]) => {
然后您可以像以前一样使用action
,而options
就是您从this.featureStore.select(fromFeature.getCurrentSearchPageOptions)
回来的
答案 1 :(得分:0)
withLatestFrom:将源Observable与其他Observables组合在一起,以创建一个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))
)
);
}
)
);