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

问题描述

  • searchFunction 在用户自动完成文本框中输入值时被调用。所以,这段代码应该做的是根据用户输入将选项返回到自动完成下拉列表,它应该只显示最后一个查询的选项。

  • 如果我使用此代码并且在其他地方调用它时不会返回任何内容(当我使用上述主题和可观察对象时)。调用这个函数的地方需要一个observable,所以我们必须从这里返回和observable。此外,我无法编辑/更改调用上述函数函数

  • 为了只获得最后的结果,我需要 switchMap。还有其他方法可以做到吗?

  • 以下代码不起作用。请建议需要更改

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

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

我会尝试这样的事情:

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