【问题标题】:Angular: FormControl valueChanges Observable triggers for all changesAngular:FormControl valueChanges Observable 触发所有更改
【发布时间】:2019-11-12 16:00:48
【问题描述】:

FormControl valueChanges Observable 像它应该的那样工作。在我的情况下,我需要停止触发valueChanges 之前输入字段中除当前值之外的所有更改。我一直在尝试使用以下代码来做到这一点-

private getAutocompleteSuggestions(input){
    return this.SS.searchProducts(parseInt(this.filter), '', input);
}


private searchSuggestionsAPIRequest(input){
    this.queryField.valueChanges
        .debounceTime(1000)
        .distinctUntilChanged()
        .switchMap((input) =>  this.getAutocompleteSuggestions(input))
        .subscribe( res => {
          // The res is triggered for all value changes in 
          // queryField formcontrol

          // Tried with following solution to stop emit previous 
          // changes but it does not work

          this.queryField.setValue(input, { emitEvent: false });

    });
} 

我一直在寻找所有可能的方法来停止发出以前的值,但得到了这个解决方案 -

this.queryField.setValue(input, { emitEvent: false });

我想,我在那里遗漏了一些东西。如果有任何进一步的解决方案或文档,那就太好了。

提前致谢。

【问题讨论】:

  • 您可能正在尝试以不同的方式实现某些目标,当您说“您想忽略以前的值”时,您能否解释一下您的情况。

标签: angular input autosuggest


【解决方案1】:

ValueChange 是一个观察值,每次你输入它都会触发发射。您可以在 switch 映射中调用您的 api,并使用来自输入的最新值订阅其结果,并保持 valueChanges 行为不变。

searchBook() {
    this.bookId.valueChanges.pipe(
      debounceTime(1000),
      distinctUntilChanged(),
      switchMap(input => {
        this.getAutocompleteSuggestions(input)).subscribe(res =>{
          //DO you required processing
        })
      })
    ).subscribe(model => model);
   }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-07
    • 2013-11-22
    • 1970-01-01
    • 2019-01-25
    • 2016-11-06
    • 1970-01-01
    相关资源
    最近更新 更多