【问题标题】:Angular 2 Using Observable.debounce() with Http.getAngular 2 使用 Observable.debounce() 和 Http.get
【发布时间】:2016-06-29 17:55:30
【问题描述】:

我了解Observable.debounce() 可用于处理速射表单输入。由于 Http GET 还返回一个 Observable,我想知道是否可以对快速 http 请求进行去抖动?我试过 debounceTime() 但它似乎没有做任何事情。

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

【问题讨论】:

  • 请添加一些代码来演示您尝试完成的工作。
  • public getStuff(p1, area:string, p2:string): Observable { return this.http.get(some_url) .map(r => r.json()) .debounceTime(10000) .catch(this.handleError); };
  • 请编辑您的问题并在此处添加代码。 cmets 中的代码很难阅读。 edit 链接位于您问题下方的 angular2 observable 标记下方。
  • 抱歉,我没想到用格式正确的代码示例来更新问题。它现在就在那里。

标签: angular observable


【解决方案1】:

debounceTime 允许缓冲事件并仅在一段时间后处理最后一个事件。

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

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

@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;
               });
  }
}

您也可能对这篇文章感兴趣:

根据 micronyks 的评论,这里是一个附加链接:

【讨论】:

  • 在现代 Angular 中,您必须将 debounceTime 和其他函数放在 pipe(..) 调用中。 IE。 :...valueChanges.pipe(debounceTime(500), distinctUntilChanged(), switchMap(..)).subscribe(..);
【解决方案2】:

在 Angular7 中:

import { Observable, of, timer } from 'rxjs';
import { catchError, retry, map, debounce } from 'rxjs/operators';

public getStuff(p1, area:string, p2:string): Observable<number> { 
   return this.http.get(some_url) 
   .pipe(
      debounce(() => timer(10000)),
      catchError(this.handleError)
   );
};

【讨论】:

  • 非常感谢现代版!
  • 我试过了,但这对我不起作用
【解决方案3】:

您必须使用 switchMap 将主题 observable 转换为 http observable,如下所示:

observableObj$: Observable<any>;
subjectObj = new Subject();

 ngOnInit() {
    this.observableObj$ = this.subjectObj.pipe(
      debounceTime(1000),
      switchMap(() => {
        ...
        return this.http.get(some_url).map(r => r.json());
      }),
    );

    this.observableObj$.subscribe((data) => {
      // result of http get...
      ...
    });
}

getStuff() {
    this.subjectObj.next();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-23
    • 2017-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多