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

社会主义新天地 提交于 2019-12-10 17:27:28

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!