How to prevent http call in Angular 2 when using observables?

A few examples show how to use observable elements to connect a control to display data received from the http backend, for example: http://blog.thoughtram.io/angular/2016/01/06/taking-advantage-of-observables- in-angular2.html

Can you prevent this HTTP call in certain situations? For example, in the mentioned record there is an autocomplete field - is there a way to prevent the http call if the user clears the field?

I tried to change the switchMap function, for example:

if(term.length < 1) {
   return Observable.empty();
}
else { // call the http service...

and this prevents the call, but leaves the previous results in the control.

+4
source share
1

, , - filter(term => term.length > 0) .

, , , ?

this.items = this.term.valueChanges
             .debounceTime(400)
             .distinctUntilChanged()
             .switchMap(term => term.length > 0 
               ? this.wikipediaService.search(term) 
               : Observable.of([]));

plunkr: http://plnkr.co/edit/3p9eqiPAcqjBIEdLNkUG?p=preview

+4

Source: https://habr.com/ru/post/1623386/


All Articles