我的构造函数中有以下代码:
this.searchResults = this.searchTerm.valueChanges .debounceTime(500) .distinctUntilChanged() .switchMap(term => this.apiService.search({ limit: this.searchResultsLimit,term: term }));
这是我的意见
<input type="text" [formControl]="searchTerm" />
我的API服务方法如下:
searchCompanies(options): Observable<any[]> { return this.jsonp.get('api/search',this.formatOptions(options)).map(res => { return res.json(); }); }
每次在输入中更改searchTerm时,都会触发API调用.我的问题是,即使我的输入为空(例如输入查询,然后将其全部退回),调用也会被触发.
我的问题是,当`searchTerm的值不为空/ null时,我怎么才能触发我的observable?
如果要避免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([]) });