2017-02-20 52 views
3

我有我的构造函数中以下代码:如何只执行一个Observable如果term不为null/empty?

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的值不为空/空值时,我怎么才能让我的observable被触发?

+0

您可以在构造函数中有一个,如果条件 – Aravind

+0

岂不是SIMPL Ÿ检查你的服务? – developer033

+0

@ developer033 - 我的服务是直观的。我现在用这个方法编辑问题。 – Fizzix

回答

4

如果你想避免API调用,并希望搜索结果被重置时,搜索词为空测试在switchMap和一个空字符串返回一个空观察到在这种情况下:

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([]) 
    }); 
+0

整洁。但不幸的是,当'term'为空/空时'searchResults'不会被清空。 – Fizzix

+2

那么,在这种情况下,如果没有匹配,您应该返回API返回的任何内容。例如,要返回一个空数组,用'Observable.of([])'替换'Observable.empty()'。 – cartant

+1

'Observable.of([])'完美地工作,谢谢。 – Fizzix

2

最容易被刚刚使用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 
    })); 
+0

无缝工作。然而,当'term'为空时,它将'this.searchResults'的问题留作API服务最后返回结果的值。如果搜索词为空,那么如何将this.searchResults设置为null或undefined? – Fizzix

+0

你的'this.searchResults'持有Observable,所以你可能不想重写它。 – martin

+0

'filter'保存了我的日期。 – KevinOrfas

相关问题