angular - 使用排气映射而不是第一个处理最新点击
问题描述
我试图只为第一次点击发出请求,并在第一次请求仍在进行时忽略所有其他后续点击。为此我使用了exhaustMap 运算符。但它似乎像 switchMap 一样工作,因为所有初始请求都被取消,只有最新的请求得到处理。
这是代码
const headers = new HttpHeaders({ Accept: "application/json" });
return this.http
.post(`${this.sUrl}/token`, null, {
headers: headers,
})
.pipe(
catchError(this.handleError),
exhaustMap((token: any) => {
oRequest.token = token.token;
headers.append("Content-Type", "application/json");
return this.http
.post(`${this.sUrl}/find`, oRequest, { headers: headers })
.pipe(catchError(this.handleError));
})
);
我究竟做错了什么?
解决方案
我用假 API 做了一个例子:https ://stackblitz.com/edit/angular7-rxjs-kyq38b?file=src%2Fapp%2Fapp.component.ts
import { Component } from "@angular/core";
import { mergeMap, exhaustMap } from "rxjs/operators";
import { HttpClient } from "@angular/common/http";
import { Subject } from "rxjs";
@Component({
selector: "my-app",
template: `
<button (click)="onSubmit()">submit</button>
`,
styleUrls: ["./app.component.css"]
})
export class AppComponent {
submit$: Subject<boolean> = new Subject();
constructor(private http: HttpClient) {}
ngOnInit() {
this.submit$
.pipe(
mergeMap(() => this.http.get(`https://swapi.dev/api/films/1/`)),
exhaustMap(film =>
this.http.get(film["characters"][0].replace("http", "https"))
)
)
.subscribe(res => {
console.log(res);
});
}
onSubmit() {
this.submit$.next(true);
}
}
您单击“提交”,并且在 HttpClient 实例返回响应并完成之前,exhaustMap() 运算符将忽略所有正在进行的单击事件。
推荐阅读
- java - 检查 ArrayList 中是否存在对象
- firebase - 如何在flutter中从firebase数据库中检索数据?
- wordpress - 有没有办法将 socket.io 添加到 Wordpress 插件?
- excel - 如何使用 xml 查询从以下网站获取数据
- python - PYTHON:将每个 CSV 行转换为单独的 XML 文件
- javascript - 如何让一个文件实时检查另一个文件数据而不是从一开始就缓存
- java - 如何在 Java 中创建间隔?
- laravel - 使用 Laravel 批量插入,无需任何循环
- android - android中的字体系列使用
- reactjs - React Native:如何根据 Scroll 或 Y contentOffset 更改状态栏样式