angular – 如果term不为null / empty,如何只执行Observable?
发布时间:2020-12-17 10:21:48 所属栏目:安全 来源:网络整理
导读:我的构造函数中有以下代码: this.searchResults = this.searchTerm.valueChanges .debounceTime(500) .distinctUntilChanged() .switchMap(term = this.apiService.search({ limit: this.searchResultsLimit,term: term })); 这是我的意见 input type="text
我的构造函数中有以下代码:
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的值不为空/ 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([]) }); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |