使用可观察对象时如何防止 Angular 2 中的 http 调用?
How to prevent http call in Angular 2 when using observables?
几个示例演示了如何使用可观察对象连接控件以显示从 http 后端获取的数据,例如:http://blog.thoughtram.io/angular/2016/01/06/taking-advantage-of-observables-in-angular2.html
你能在某些情况下阻止那个 http 调用吗?例如,在提到的 post 中有一个自动完成字段 - 有没有办法在用户清除该字段的情况下阻止 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([]));
正在工作的 plunkr:http://plnkr.co/edit/3p9eqiPAcqjBIEdLNkUG?p=preview
几个示例演示了如何使用可观察对象连接控件以显示从 http 后端获取的数据,例如:http://blog.thoughtram.io/angular/2016/01/06/taking-advantage-of-observables-in-angular2.html
你能在某些情况下阻止那个 http 调用吗?例如,在提到的 post 中有一个自动完成字段 - 有没有办法在用户清除该字段的情况下阻止 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([]));
正在工作的 plunkr:http://plnkr.co/edit/3p9eqiPAcqjBIEdLNkUG?p=preview