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()
运算符过滤掉所有空term
s:
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)
如果要避免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)
归档时间: |
|
查看次数: |
10157 次 |
最近记录: |