如何在ngrx效果中进行http轮询 [英] How to do http polling in ngrx effect
问题描述
我有这种效果,我正在尝试使用计时器每x秒轮询一次数据.但是我无法弄清楚计时器应该如何与数据流交互.我尝试在顶部添加另一个switchMap,但是后来我无法将操作和有效负载传递给第二个switchmap.有什么想法吗?
I have this effect, and I'm trying to use timer to poll for data every x seconds. But I can't figure out how timer is supposed to interact with the data streams. I tried adding another switchMap to the top, but then I couldn't pass the action and payload to the second switchmap. Any ideas?
我查看了这篇文章但是我的情况有些不同.我正在通过需要访问的操作传递有效负载,并且正在使用ngrx 6.
I looked at this post but my situation is a little different. I'm passing a payload with my action that I need to access, and I'm using ngrx 6.
@Effect()
getData = this.actions$
.ofType(appActions.GET_PLOT_DATA)
.pipe(
switchMap((action$: appActions.GetPlotDataAction) => {
return this.http.post(
`http://${this.url}/data`,
action$.payload.getJson(),
{responseType: 'json', observe: 'body', headers: this.headers});
}),
map((plotData) => {
return {
type: appActions.LOAD_DATA_SUCCESS,
payload: plotData
}
}),
catchError((error) => throwError(error))
)
推荐答案
这应该有效(我已经对其进行了测试).请在switchMap
的顶部添加.此处的关键操作员是mapTo
.该运算符会将间隔的输入值映射到有效负载中.
This should work (i have tested it). Please add this top of the switchMap
. The key operator here is the mapTo
. This operator will map the incoming value of the interval into the payload.
switchMap((action$: appActions.GetPlotDataAction) =>
interval(5000).pipe(mapTo(action$))
);
更新(提示):
-如果要立即开始轮询,然后每{n} ms开始,可以使用startWith
运算符或timer
observable
Update (hint):
- If you want to start immediately with the polling and then each {n}ms you can use the startWith
operator or the timer
observable
switchMap((action$: appActions.GetPlotDataAction) =>
interval(5000).pipe(startWith(0), mapTo(action$))
);
或
switchMap((action$: appActions.GetPlotDataAction) =>
timer(0, 1000).pipe(mapTo(action$))
);
这篇关于如何在ngrx效果中进行http轮询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!