单击按钮时,将触发 getDatafromServer 方法。告诉我 switchMap 是否在 Angular 中为一条路线正确实现,即 再次按下时,前一个请求被取消(如果旧请求尚未到达)并发送新请求:
getDatafromServer() {
of(`url1`).pipe(switchMap(url => this.httpGeneralService.getDataFromJsonServer(url))).
subscribe(i => console.log(i));
}
一切似乎都是正确的,但在网络上的浏览器中,以前的请求被取消是不可见的
UPD:此选项似乎有效:
private requestPasswordSubject$ = new Subject();
private requestPassword = this.requestPasswordSubject$.pipe(
switchMap(() => this.httpGeneralService.getDataFromJsonServer(`url1`))
)
.subscribe(response => { console.log(response); } );
getDatafromServer() {
this.requestPasswordSubject$.next();
}
switchMap如果按钮单击事件来自线程,则将正常工作。在这种情况下:of('url1')- 这是一个冷线程,将生成一个事件 1 次并关闭(问题是你为什么要这样做?)我会说这是无用的代码。如果您想通过单击按钮发送请求并取消订阅流,如果没有响应到达,但有新事件到达,您需要使用链接
fromEvent + switchMap:switchMap订阅流fromEvent,将工厂作为参数(在 RxJS 概念中,这称为投影),调用此工厂并接收新的流作为结果(返回this.httpGeneralService.getDataFromJsonServer('url1')),订阅此流,等待响应,如果它fromEvent在流之前生成事件getDataFromJsonServer-SwitchMapSubscriber取消订阅getDataFromJsonServer并处理来自流的新流事件fromEvent。