首页 > 解决方案 > RxJS debounceTime(0) still postpones execution

问题描述

I am using Angular 7 and latest RxJS and ngrx/store. I faced a problem with debounceTime(0). debounceTime is an @Input() property of ui-input component. Its default value is 0. I want a possibility to use debounceTime for some inputs - for others - no. The input value I am getting from the store. Also, I have a validation service that should validate input values. I pass the input value to validation service through the selector. The problem is that in validation service I am getting previous values. Here is a simplified (updated) example. I have validation rule: input.length > 2. I want to get an error when the length is more than 2. But with debounceTime(0) I am getting a validation error in the console only when the length of the input is 4.

If I remove debounceTime - everything work as expected. I am getting a synchronous call:

How I can fix the problem? I didn't find any variants for applying debounceTime conditionally. Also, I think that something like this is not a good solution:

ngOnInit() {
    if (this.debounceTime > 0) {
      this._valueChanged
        .pipe(
          debounceTime(this.debounceTime),
        )
        .subscribe(value => this.inputted.emit(value));
    } else {
      this._valueChanged
        .subscribe(value => this.inputted.emit(value));
    }
  }

标签: javascriptangularrxjs6

解决方案


您不应该从 Subject 或 BehaviorSubject 获取值,而是应该订阅它。

store.service.ts

所以下面的代码应该改变

  process() {
    console.log('Store:   ', this.value$.getValue());
  }

 constructor(){
    this.value$.subscribe(v=>{
      console.log('Store:   ', v);
    })
  }

您不需要手动调用 store 函数,因此您也可以将其删除。

工作示例代码在这里 - https://stackblitz.com/edit/angular-5ajqn9


推荐阅读