typescript 如果 term 不为空/空,如何仅执行 Observable?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42334602/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to only execute an Observable if term is not null/empty?
提问by Fizzix
I have the following code inside my constructor:
我的构造函数中有以下代码:
this.searchResults = this.searchTerm.valueChanges
.debounceTime(500)
.distinctUntilChanged()
.switchMap(term => this.apiService.search({
limit: this.searchResultsLimit,
term: term
}));
And this is my input
这是我的输入
<input type="text" [formControl]="searchTerm" />
You can see the tutorial I followed to get the code here.
您可以在此处查看我遵循的教程以获取代码。
My API service method is as followed:
我的API服务方法如下:
searchCompanies(options): Observable<any[]> {
return this.jsonp.get('api/search', this.formatOptions(options)).map(res => {
return res.json();
});
}
Each time searchTerm
is changed inside my input, the API call is fired. My problem is that the call is fired even when my input is empty (such as typing a query, then backspacing it all).
每次searchTerm
在我的输入中更改时,都会触发 API 调用。我的问题是,即使我的输入为空(例如输入查询,然后全部退格),调用也会被触发。
My question is, how can I only get my observable to fire when the value of `searchTerm is not empty/null?
我的问题是,当`searchTerm 的值不为空/空时,我怎样才能让我的 observable 触发?
采纳答案by cartant
If you want to avoid the API call and want the search results to be reset when the search term is empty, test for an empty string in switchMap
and return an empty observable in that situation:
如果您想避免 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([])
});
回答by martin
Most easily just use the filter()
operator to filter out all empty term
s:
最简单的方法是使用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
}));