【问题标题】:How to do http polling in ngrx effect如何在ngrx效果中进行http轮询
【发布时间】:2018-09-10 19:04:48
【问题描述】:

我有这个效果,我正在尝试使用计时器每 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))
    )

【问题讨论】:

标签: angular http rxjs ngrx ngrx-effects


【解决方案1】:

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

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

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

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

或

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

更新 (15.04.2021):

例如,使用 takeUntil 和 Subject 可以一次停止轮询流,就像这样在代码中的某个位置。当有人点击某物时,您也可以杀死。这取决于您和用例。

const kill$ = new Subject();
switchMap((action$: appActions.GetPlotDataAction) => 
  timer(0, 1000).pipe(mapTo(action$), takeUntil(kill$))
);

// killing for example after 60 seconds
setTimeout(() => kill$.next(), 60000);

【讨论】:

  • 工作就像一个魅力!谢谢。我没有使用 mapTo 运算符,真的很有用。而且我想我混淆了计时器和间隔。谢谢@Bitcollage!
  • @FussinHussin 很高兴听到这个消息。
  • 感谢更新,我刚想说第一次调用受到影响,但第二次实现已修复
  • 是的,请作为第一个参数添加到管道skip(1):interval(5000).pipe(skip(1), mapTo(action$)))。 skip(1) 将跳过第一次调用。
  • 以及如何停止间隔?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-23
  • 2018-10-05
  • 2018-01-11
  • 2018-10-08
  • 2020-08-07
相关资源
最近更新 更多