首页 > 解决方案 > 使用排气映射而不是第一个处理最新点击

问题描述

我试图只为第一次点击发出请求,并在第一次请求仍在进行时忽略所有其他后续点击。为此我使用了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));
        })
      );

我究竟做错了什么?

标签: angularrxjs

解决方案


我用假 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() 运算符将忽略所有正在进行的单击事件。


推荐阅读