Angular 5在方法上使用debounceTime

时间:2018-03-07 11:37:58

标签: angular rxjs

我正在尝试在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 个答案:

答案 0 :(得分: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();
}

答案 1 :(得分: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);
    }
    ...
}

答案 2 :(得分: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);
    }
    ...
}