每个服务器响应+延迟后轮询服务器 [英] Polling server after each server response + delay
问题描述
我正在制作一个效果器,它将是轮询服务器.
I am working on an effect, that will be polling server.
我要实现的目标如下:
1)将GET请求发送到服务器
1) Send GET request to server
2)收到响应后,等待3秒钟
2) After response is received, wait 3 seconds
3)发送相同的GET请求
3) Send same GET request
4)收到响应后,等待3秒钟
4) After response is received, wait 3 seconds
5)发送相同的GET请求
5) Send same GET request
...等等.
我现在拥有的代码无法正常工作,因为它每3秒轮询一次服务器,无论是否收到响应:
The code that I have now, doesn't quite work, as it polls server every 3 seconds, no matter if response was received or not:
@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
动作,那么它可以正常工作-但是,如果我在请求发送之后发出它,那么我将在轮询停止之前再收到一个后续响应.
Another thing that I am struggling with is how to stop polling. If I emit StopPollingSubnetEntries
action before request is sent to server, then it works fine - however if I emit it after request is sent, then I receive one more subsequent response, before polling stops.
推荐答案
您可以使用expand
连续映射到下一个http请求并预先添加delay
.
You could use expand
to continuously map to the next http request and add a delay
beforehand.
const stopPolling$ = this.actions$.pipe(
ofType(SubnetBrowserPageActions.SubnetBrowserPageActionTypes.StopPollingSubnetEntries)
);
const httpRequest$ = this.subnetBrowserService.getSubnetEntries().pipe(
map(entries => new SubnetBrowserApiActions.LoadEntriesSucces({ entries })),
catchError(error => of(new SubnetBrowserApiActions.LoadEntriesFailure({ error })))
)
const pollEntries$ = this.httpRequest$.pipe(
expand(_ => of(1).pipe(
delay(3000),
mergeMap(_ => this.httpRequest$),
)),
takeUntil(this.stopPolling$)
);
要开始轮询,您必须订阅pollEntries$
.
To start polling you have to subscribe to pollEntries$
.
startPolling() {
this.pollEntries$.subscribe(entries => console.log(entries));
}
或者在您的操作发出时映射到pollEntries
.
Or map to the pollEntries
whenever your action emits.
const pollEntriesOnAction$ = this.actions$.pipe(
ofType(SubnetBrowserPageActions.SubnetBrowserPageActionTypes.StartPollingSubnetEntries),
switchMap(() => this.pollEntries$)
);
this.pollEntriesOnAction$.subscribe(entries => console.log(entries));
https://stackblitz.com/edit/angular-mu3kp5
这篇关于每个服务器响应+延迟后轮询服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!