switchMap 未使用以下代码取消先前的请求

switchMap is not canceling the previous request with below code

export class AppComponent {
  readonly search = new ReplaySubject<string>(1);
  searchResponse!: Observable<string[]>;

  constructor(private http: HttpClient) {}

  searchFunction = (query: string) => {
    return (this.searchResponse = this.search.pipe(
      debounceTime(300),
      distinctUntilChanged(),
      switchMap((query: string) => {
        return this.http.searchData(query).pipe(
          map((res: string[]) => {
            return res.slice(0, 100);
          })
        );
      })
    ));
  };
}

在本文中,您可以找到使用 RxJS 运算符的完整实现 - 请参阅“Search TypeAhead - switchMap 运算符示例”部分 - 希望对您有所帮助!

https://blog.angular-university.io/rxjs-higher-order-mapping/

问题在于:

searchFunction is being called when a user enters value in autocomplete textbox

每次调用该函数时都会创建一个新的订阅。虽然模板应该退订之前的订阅,但解决方案并不理想。

我会尝试这样的事情:

export class AppComponent {
  readonly search = new Subject<string>();
  readonly searchResponse: Observable<string[]>;

  constructor(private http: HttpClient) {
    this.searchResponse = this.search.pipe(
      debounceTime(300),
      distinctUntilChanged(),
      switchMap((query: string) => {
        return this.http.searchData(query).pipe(
          map((res: string[]) => {
            return res.slice(0, 100);
          }),
          // So we don't wreck the pipe. Import EMPTY from 'rxjs'
          catchError(() => EMPTY)
        );
      })
  }

  searchFunction = (query: string) => {
    this.search.next(query);
  };
}

在这种情况下,您对搜索词只有一次订阅。如果您使用的是响应式表单,则可以收听 valueChanges.