如果 term 不是 null/empty,如何只执行一个 Observable?

How to only execute an Observable if term is not null/empty?

我的构造函数中有以下代码:

this.searchResults = this.searchTerm.valueChanges
    .debounceTime(500)
    .distinctUntilChanged()
    .switchMap(term => this.apiService.search({
        limit: this.searchResultsLimit,
        term: term
    }));

这是我的输入

<input type="text" [formControl]="searchTerm" />

您可以查看我获取代码的教程here

我的API服务方式如下:

searchCompanies(options): Observable<any[]> {
    return this.jsonp.get('api/search', this.formatOptions(options)).map(res => {   
        return res.json();
    });
}

每次在我的输入中更改 searchTerm 时,都会触发 API 调用。我的问题是,即使我的输入为空(例如输入查询,然后全部退格),调用也会被触发。

我的问题是,当 `searchTerm 的值不是 empty/null 时,如何才能让我的 observable 触发?

最简单的方法就是使用 filter() 运算符过滤掉所有空的 terms:

this.searchResults = this.searchTerm.valueChanges
    .filter(term => term) // or even better with `filter(Boolean)`
    .debounceTime(500)
    .distinctUntilChanged()
    .switchMap(term => this.apiService.search({
        limit: this.searchResultsLimit,
        term: term
    }));

如果您想避免调用 API 并希望在搜索词为空时重置搜索结果,请在 switchMap 和 return 中测试空字符串在这种情况下可观察到空值:

this.searchResults = this.searchTerm
  .valueChanges
  .debounceTime(500)
  .distinctUntilChanged()
  .switchMap(term => term ?
    this.apiService.search({
      limit: this.searchResultsLimit,
      term: term
    }) :
    // If search term is empty, return an empty array
    // or whatever the API's response for no matches
    // would be:
    Observable.of([]) 
  });

在 Rxjs 6 中更新为使​​用 pipe 您可以停止处理可观察对象,因此使用 EMPTY:

不会向下游传播任何内容
this.searchResults = this.searchTerm.valueChanges
    .pipe(
      debounceTime(500)
      distinctUntilChanged()
      switchMap(term => 
        (term) 
          // If the term exists make a request
          ? this.apiService.search({ limit: this.searchResultsLimit, term: term })
          // Otherwise, stop all processing
          : EMPTY
      )
    )
);