如何在ngrx效果中进行http轮询

时间:2018-09-10 19:04:49

标签: angular http rxjs ngrx ngrx-effects

我有这种效果,我正在尝试使用计时器每x秒轮询一次数据。但是我不知道计时器应该如何与数据流交互。我尝试在顶部添加另一个switchMap,但随后无法将操作和有效负载传递给第二个switchmap。有什么想法吗?

我看过this post,但情况略有不同。我正在通过需要访问的操作传递有效负载,并且正在使用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))
    )

1 个答案:

答案 0 :(得分:4)

这应该工作(我已经测试过)。请在switchMap的顶部添加。这里的关键运算符是mapTo。该运算符会将间隔的输入值映射到有效负载中。

switchMap((action$: appActions.GetPlotDataAction) =>
   interval(5000).pipe(mapTo(action$))
);

更新(提示): -如果您想立即开始轮询,然后每{n} ms开始使用startWith运算符或timer可观察的

switchMap((action$: appActions.GetPlotDataAction) =>
  interval(5000).pipe(startWith(0), mapTo(action$))
);

switchMap((action$: appActions.GetPlotDataAction) => 
  timer(0, 1000).pipe(mapTo(action$))
);
相关问题