【发布时间】:2023-04-10 00:57:01
【问题描述】:
我正在制作一个效果,即轮询服务器。
我想要达到的效果如下:
1) 向服务器发送 GET 请求
2) 收到响应后,等待 3 秒
3) 发送相同的 GET 请求
4) 收到响应后,等待 3 秒
5) 发送相同的 GET 请求
...等等。
我现在的代码不太好用,因为它每 3 秒轮询一次服务器,无论是否收到响应:
@Effect()
pollEntries$ = this.actions$.pipe(
ofType(SubnetBrowserPageActions.SubnetBrowserPageActionTypes.StartPollingSubnetEntries),
switchMap(() => {
return timer(0, 3000);
}),
takeUntil(this.actions$.pipe(ofType(SubnetBrowserPageActions.SubnetBrowserPageActionTypes.StopPollingSubnetEntries))),
switchMap(() => {
return this.subnetBrowserService.getSubnetEntries();
}),
map((entries) => {
return new SubnetBrowserApiActions.LoadEntriesSucces({ entries });
}),
catchError((error) => {
return of(new SubnetBrowserApiActions.LoadEntriesFailure({ error }));
}),
);
我正在努力解决的另一件事是如何停止投票。如果我在请求发送到服务器之前发出 StopPollingSubnetEntries 操作,那么它工作正常 - 但是如果我在发送请求后发出它,那么我会在轮询停止之前收到一个后续响应。
【问题讨论】:
-
如果收到错误响应,是否要停止轮询?
-
不,我只想在发出“StopPollingSubnetEntries”操作后停止轮询。
标签: angular rxjs ngrx rxjs6 ngrx-effects