Angular 5 中如何在方法上使用 debounceTime

4

我正在尝试在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 => {
        // -
    });
}

有没有一种像saveData().debounceTime()这样的方法?还是我需要用其他方法来实现?
3个回答

7
我不确定,但是这种方法可能有效:

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

在您的构造函数或init中:
this.$save
  .debounceTime(400)
  .switchMap(() => this.http.post(...post params))
  .subscribe(..Do something);

你的保存方法:

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

1

// "rxjs": "^6.3.3"
import { Subject } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
...
export class SomeClass {    
    ...
    $subject: Subject<string> = new Subject<string>();


    constructor() {
        this.$subject.pipe(debounceTime(1000)).subscribe((event: string) => runMethod(event));
    }

    onSomeMethod(event: string) {
        this.$subject.next(event);
    }

    private runMethod(event: string) {
        // do stuff
        console.log(event);
    }
    ...
}


1
把这个放在这里。
// "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);
    }
    ...
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接