首页 文章

Angular 5在方法上使用debounceTime

提问于
浏览
2

我试图在Angular 5函数上使用debounceTime,但我不确定如何使用它 . 当我构建一个搜索函数时,我可以使用它,因为它绑定了对该输入值所做的更改,如下所示:

this.search
    .debounceTime(400)
    .distinctUntilChanged()
    .takeUntil(this.onDestroy)
    .subscribe((model) => {
        return this.filterArray(model);
    });

但现在我想将它应用于一个函数,这个函数是从很多地方调用的,并通过http post将事件发送到数据库,如下所示:

private saveData(): void {
    this.http.post('event/url', data).takeUntil(this.onDestroy).subscribe((response: Response) => {
        // -
    }, error => {
        // -
    });
}

有没有办法像_2979524那样做?或者我需要以其他方式做到这一点?

2 回答

  • 4

    我不确定,但这样的事可能有效:

    $save: Subject<void> = new Subject<void>();
    

    在你的构造函数或init中:

    this.$save
      .debounceTime(400)
      .switchMap(() => this.http.post(...post params))
      .subscribe(..Do something);
    

    你的保存方法:

    saveData(){
        this.$save.next();
    }
    
  • 0

    把它放在这里

    // "rxjs": "^6.2.0",
    //import { Subject } from 'rxjs';
    //import { debounceTime, distinctUntilChanged } from 'rxjs/operators';
    ...
    export class SomeClass {    
        ...
        $subject: Subject<void> = new Subject<void>();
    
    
        constructor() {
            this.$subject.pipe(debounceTime(2000), distinctUntilChanged());
        }
    
        onSomeMethod(event: string) {
            this.$subject.next(this.runMethod(event));
        }
    
        runMethod(event: any) {
            // do stuff
            console.log(event);
        }
        ...
    }
    

相关问题