使用 observables 时如何防止 Angular 2 中的 http 调用?

2024-01-02

几个示例演示了如何使用可观察量连接控件以显示从 http 后端获取的数据,例如:http://blog.thoughtram.io/angular/2016/01/06/take-advantage-of-observables-in-angular2.html http://blog.thoughtram.io/angular/2016/01/06/taking-advantage-of-observables-in-angular2.html

在某些情况下你能阻止 http 调用吗?例如,在提到的帖子中,有一个自动完成字段 - 有没有办法在用户清除该字段时阻止 http 调用?

我尝试修改 switchMap 函数,例如:

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

它确实阻止了调用,但将先前的结果保留在控件中。


抱歉,我在移动设备上,但是类似filter(term => term.length > 0)应该可以解决问题。

评论后更新

可能有更优雅的方法来处理这个问题,但是这个怎么样?

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

工作笨蛋:http://plnkr.co/edit/3p9eqiPAcqjBIEdLNkUG?p=preview http://plnkr.co/edit/3p9eqiPAcqjBIEdLNkUG?p=preview

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 observables 时如何防止 Angular 2 中的 http 调用? 的相关文章

随机推荐