Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/http/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 如何在ngrx效果中进行http轮询_Angular_Http_Rxjs_Ngrx_Ngrx Effects - Fatal编程技术网

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

Angular 如何在ngrx效果中进行http轮询,angular,http,rxjs,ngrx,ngrx-effects,Angular,Http,Rxjs,Ngrx,Ngrx Effects,我有这样的效果,我尝试使用定时器每x秒轮询一次数据。但我不知道计时器应该如何与数据流交互。我尝试向顶部添加另一个开关映射,但随后无法将操作和负载传递给第二个开关映射。有什么想法吗 我看了一下,但我的情况有点不同。我正在传递一个有效载荷和我需要访问的操作,我正在使用ngrx 6 @Effect() getData = this.actions$ .ofType(appActions.GET_PLOT_DATA) .pipe( switchMap((action$:

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

我看了一下,但我的情况有点不同。我正在传递一个有效载荷和我需要访问的操作,我正在使用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((action$: appActions.GetPlotDataAction) =>
   interval(5000).pipe(mapTo(action$))
);
更新(提示): 如果要立即开始轮询,然后每次{n}毫秒,可以使用
startWith
操作符或
计时器
可观察

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

更新(2021年4月15日):

例如,对于TakeTill和主题,您可以在代码中的某个地方一次停止轮询流,如下所示。当有人点击某个东西时,你也可以杀人。这取决于您和用例

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);

试试这个谢谢,我已经看过了,不过我用的是RXJS 6,我的动作有一个有效载荷。所以我还没能让它像符咒一样工作!谢谢我没有使用mapTo操作符,非常有用。我猜我把计时器和时间间隔搞混了。谢谢@Bitcollage@FussinHussin很高兴听到。感谢您的更新,我正要说第一个调用受到影响,但第二个实现已经修复了。是的,当然,请将作为第一个参数添加到管道
skip(1)
interval(5000)。管道(skip(1),mapTo(action$))
。跳过(1)将跳过第一次呼叫。如何停止间隔?
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);