如果term不为null/empty,如何只执行Observable?

Fiz*_*zix 10 observable rxjs typescript rxjs5 angular

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

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

这是我的意见

<input type="text" [formControl]="searchTerm" />
Run Code Online (Sandbox Code Playgroud)

你可以看到我在这里获得代码的教程.

我的API服务方法如下:

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

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

我的问题是,当`searchTerm的值不为空/ null时,我怎么才能触发我的observable?

mar*_*tin 23

最容易使用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
    }));
Run Code Online (Sandbox Code Playgroud)

  • 使用过滤器作为`.filter(term =&gt; term != null)` (5认同)

car*_*ant 5

如果要避免API调用并希望在搜索项为空时重置搜索结果,请测试空字符串switchMap并在该情况下返回空的observable:

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([]) 
  });
Run Code Online (Sandbox Code Playgroud)

  • 那么,在这种情况下,如果没有匹配,你应该返回API返回的任何内容.例如,要返回一个空数组,请将`Observable.empty()`替换为`Observable.of([])`. (3认同)