问题
Several examples demonstrate how to use observables to hook up a control to show data fetched from a http backend, such as this one: http://blog.thoughtram.io/angular/2016/01/06/taking-advantage-of-observables-in-angular2.html
Can you prevent that http call in certain situations? For example in the mentioned post there is an autocomplete field - is there a way to prevent the http call in case the user clears the field?
I have tried modifying the switchMap function with for example:
if(term.length < 1) {
return Observable.empty();
}
else { // call the http service...
and it does prevent the call, but leaves the previous results at the control.
回答1:
Sorry, I'm on mobile but something like filter(term => term.length > 0) should do the trick.
UPDATE after comment
There are probably more elegant ways of handling this but how about this?
this.items = this.term.valueChanges
.debounceTime(400)
.distinctUntilChanged()
.switchMap(term => term.length > 0
? this.wikipediaService.search(term)
: Observable.of([]));
Working plunkr: http://plnkr.co/edit/3p9eqiPAcqjBIEdLNkUG?p=preview
来源:https://stackoverflow.com/questions/34670868/how-to-prevent-http-call-in-angular-2-when-using-observables