如何prevent HTTP调用角2使用时,可观察? [英] How to prevent http call in Angular 2 when using observables?

查看:113
本文介绍了如何prevent HTTP调用角2使用时,可观察?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几个例子演示了如何使用观测挂钩的控制,显示从HTTP后端读取的数据,比如这个:的http://blog.thoughtram.io/angular/2016/01/06/taking-advantage-of-observables-in-angular2.html

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

你能prevent的HTTP在某些情况下打电话?例如,在提到后有一个自动完成场 - 是有办法prevent HTTP调用的情况下,用户清除字段

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?

我试图修改与switchMap功能,例如:

I have tried modifying the switchMap function with for example:

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

和它prevent电话,但在控制离开previous结果。

and it does prevent the call, but leaves the previous results at the control.

推荐答案

对不起,我在移动,但像滤波器(长期=&GT; term.length大于0)应该做的伎俩。

Sorry, I'm on mobile but something like filter(term => term.length > 0) should do the trick.

注释后更新

有可能处理这个更优雅的方式,但这个怎么样?

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

工作plunkr: http://plnkr.co/edit/3p9eqiPAcqjBIEdLNkUG?p= preVIEW

这篇关于如何prevent HTTP调用角2使用时,可观察?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆