首页 > 解决方案 > rxjs switchMap 类型不匹配问题

问题描述

我正在尝试在我的应用程序中使用 ng-bootstrap 实现预输入。我正在关注使用 WikipediaService获取数据的wikipedia 示例。

我在我的应用程序中实现了类似的东西,但是我在switchMap函数中遇到了类型不匹配的问题rxjs

来自 ng-bootstrap 的示例:

search = (text$: Observable<string>) =>
  text$.pipe(
    debounceTime(300),
    distinctUntilChanged(),
    tap(() => this.searching = true),
    switchMap(term =>
      this._service.search(term).pipe(
        tap(() => this.searchFailed = false),
        catchError(() => {
          this.searchFailed = true;
          return of([]);
        }))
    ),
    tap(() => this.searching = false)
  )

我的问题是,当我尝试实现此功能时,terminsideswitchMap是 anObservable<{}>而不是 a string,因此我无法将其传递给我的服务。

如何从可观察对象中获取实际值以传递给我的服务?

我的版本:

search = (text$: Observable<string>) =>
  text$.pipe(
    debounceTime(300),
    distinctUntilChanged(),
    tap(() => this.searching = true),
    switchMap(term =>
      this.placeService.search(term).pipe(  // [ts] Argument of type 'Observable<{}>' is not assignable to parameter of type 'string'. 
        tap(() => this.searchFailed = false),
        catchError(() => {
          this.searchFailed = true;
          return of([]);
        })
    ),
    tap(() => this.searching = false))
  )

更新 1

StackBlitz 演示。如果你看app\app.component.ts,你会得到 TS linting 错误。

标签: angularrxjsng-bootstrap

解决方案


根据我的评论,您遇到了括号问题。在这里,工作

/*
  Observables are streams that can be monitored. It means that when you 
  subscribe to it, everytime a value is emitted, your subscribe function 
  will be triggered (or in this case, the pipe functions, because you
  subscribe to search() in another component)
*/
search(text$: Observable<string>) {
  return text$
    // pipe = perform operations on the value before sending it to subscribe
    .pipe(
      // debounceTime = wait 300ms before emitting. If a new value is emitted,
      // cancel the previous one
      debounceTime(300),
      // distinctUntilChanged = if the value is the same as the previous one, cancel
      distinctUntilChanged(),
      // tap = perform an operation without touching the value emitted
      tap(() => this.searching = true),
      // switchMap = cancel previous HTTP requests if they're not finished
      switchMap(term => this.placeService.search(term).pipe(
      tap(() => this.searchFailed = false),
      // catchError = self-explanatory :)
      catchError(() => {
        this.searchFailed = true;
        return of([]);
      })
    )),
      tap(() => this.searching = false)
    )
};

推荐阅读