微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

我如何使用 rxjs 实现去抖动?

如何解决我如何使用 rxjs 实现去抖动?

我想实现去抖动。

Vanilla java 脚本代码看起来像这样

onInputChange(ev) {
    clearTimeout(this.timer);
    this.timer = setTimeout(() => {
      this.http.get('https://jsonplaceholder.typicode.com/users').subscribe(users => console.log('users',users));
    },700)
  }

但是我在我的角度组件中找不到对 rxjs 执行相同操作的方法

我试过了

我找到了 debounceTime 运算符,但它仍然每次都发出请求。没有1000毫秒的延迟

this.http.get('https://jsonplaceholder.typicode.com/users')
    .pipe(debounceTime(1000))
    .subscribe(users => console.log('users',users));

我也试过

<input [(ngModel)]="newUser" (input)="onInputChange($event)" [formControl]="newUserControll"/>

   this.newUserControll.valueChanges.pipe(
    debounceTime(1000)
    switchMap(() => interval(1000))).subscribe(x => console.log('x',x))

但我明白

',' expected. 错误

解决方法

这是实现 debounceTime 的示例代码

示例堆栈闪电战 - https://stackblitz.com/edit/angular-ivy-tsqwh9?file=src/app/app.component.ts

df[s == 'LHL']
,

正如其他人所提到的,您的问题是您在 http 调用之后 放置了去抖动。您必须在 http 调用之前 去抖动。

不正确的流程:

  • 值变化 -> http 调用 -> 去抖动

正确的流程:

  • 值变化 -> 去抖动 -> http 调用

正确使用switchMap的方法是这样的:

  data$ = this.newUserControl.valueChanges.pipe(
    debounceTime(1000),switchMap(userInfo => this.http.get(...))
  );

这是您可以玩的示例 StackBlitz 演示。

,

您不能在 http 请求中使用 debounceTime,您可以使用 Subject

import { Subject } from 'rxjs';
import { debounceTime } from 'rxjs/operators';

export class MyComponent {
  inputChange$ = new Subject();

  ngOnInit() {
    // create listener with debounceTime
    this.inputChange$.pipe(debounceTime(500)).subscribe({
      next: () => {
        // now make http call
        this.httpCall();
      }
    })
  }

  onInputChange() {
    // emit change
    this.inputChange$.next();
  }
  
  private httpCall() {
    this.http.get('https://jsonplaceholder.typicode.com/users').subscribe(users => console.log('users',users));
  }

}

,

假设在输入更改时,您想要调用带有一些 debounceTime 的 API。在您的 HTML 中,您需要绑定该属性以获取如下搜索文本。 如果您看到与 ngModel 相关的错误,请确保已导入:

从'@angular/forms'导入{FormsModule};

<input placeholder="Search" [(ngModel)]="searchBy"(ngModelChange)="changed.next()" name="searchBy">

在您的 .ts 文件中:

public searchBy = '';
public changed = new Subject<string>();

ngOnInit() {
   this.changed.debounceTime(300).subscribe(() => {
       this.http.get('https://jsonplaceholder.typicode.com/users').subscribe(users => {
         console.log('users',users))
       });
   });
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。