rxjs switchMap类型不匹配问题

时间:2018-09-06 11:37:24

标签: angular rxjs ng-bootstrap

我正在尝试在我的应用中使用ng-bootstrap进行预输入。我关注的是wikipedia example,它使用WikipediaService获取数据。

我在应用中实现了类似的功能,但是在switchMap的{​​{1}}函数中存在类型不匹配的问题。

来自ng-bootstrap的示例:

rxjs

我的问题是,当我尝试实现此功能时,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) ) 中的termswitchMap而不是Observable<{}>,所以我无法将其传递给我的服务。

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

我的版本:

string

更新1

StackBlitz Demo。如果您查看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)) ) ,则会看到TS掉毛错误。

1 个答案:

答案 0 :(得分:1)

在我发表评论之后,您遇到了括号问题。 Here it is, working

/*
  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)
    )
};