Angular 2将Observable.debounce()与Http.get一起使用 [英] Angular 2 Using Observable.debounce() with Http.get

查看:84
本文介绍了Angular 2将Observable.debounce()与Http.get一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道Observable.debounce()可用于处理 快速射击 表单输入.由于Http GET还返回了一个Observable,我想知道是否可以对快速的HTTP请求进行反跳?我尝试了 debounceTime() ,但似乎没有任何作用.

I understand that Observable.debounce() can be used to process rapid fire form input. As Http GET also returns an Observable, I wonder it it is possible to debounce rapid http requests? I tried debounceTime() but it did not appear to do anything.

public getStuff(p1, area:string, p2:string): Observable<number> { 
   return this.http.get(some_url) 
   .map(r => r.json()) 
   .debounceTime(10000) 
  .catch(this.handleError); 
};

推荐答案

debounceTime允许缓冲事件,并且仅在一段时间后才处理最后一个事件.

The debounceTime allows to buffer events and only handle the last one after an amount of time.

它在输入的上下文中很有用,但应在触发事件的可观察对象上定义,而不是在为HTTP请求创建的事件上定义.

It's useful in the context of inputs but it should be defined on the observable that triggers the event not on the one created for the HTTP request.

以下是与使用debounceTime运算符的输入关联的控件上的示例:

Here is a example on a control associated with an input that leverages the debounceTime operator:

@Component({
  (...)
  template: `
    <input [ngFormControl]="ctrl"/>
  `
})
export class MyComponent {
  constructor() {
    this.ctrl = new Control();
    this.ctrl.valueChanges
               .debounceTime(500)
               .distinctUntilChanged()
               .switchMap((value: string) => {
                 // Get data according to the filled value
                 return this.service.getData(entry);
               })
               .subscribe(data => {
                 // Update the linked list
                 this.list = data;
               });
  }
}

本文也可能使您感兴趣:

This article could also interest you:

  • https://jaxenter.com/reactive-programming-http-and-angular-2-124560.html (see section "Linking with user events")

在micronyks的评论之后,还有一个附加链接:

Following the micronyks's comment, here is an additional link:

  • Everything is a stream: http://slides.com/robwormald/everything-is-a-stream (youtube: https://www.youtube.com/watch?v=UHI0AzD_WfY)

这篇关于Angular 2将Observable.debounce()与Http.get一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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