4

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
  • You are close. Observable.empty creates and Observable that never fires. You need one that fires with an empty array to clear the list. Commented Jan 14, 2016 at 0:00

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

This does prevent the call, but it doesn't erase the existing list.
awesome solution! say I need a full function instead of one line =>, how do I return the original observable to be subscribed to? see: dropbox.com/s/pvt03jo6ndsw30u/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.