代码之家  ›  专栏  ›  技术社区  ›  gog

如何观察rxjs中的属性更改?

  •  2
  • gog  · 技术社区  · 6 年前

    我有一个带有简单输入标记的angular6应用程序:

    <input type="text" name="searchBox" [(ngModel)]="searchTerm" class="form-control" />
    

    我想对 searchTerm 属性添加一些运算符,如 debounce 等等等等等等。

    我如何才能做到这一点(不使用 ReactiveForms )?

    1 回复  |  直到 6 年前
        1
  •  4
  •   peinearydevelopment    6 年前

    有几种方法可以实现这一点。我发现最简单的方法如下:

    模板应包含:

    <input
      #searchInput
      [(ngModel)]="searchTerm"
      type="text"
      (keyup)="onChange(searchInput.value)" />
    

    组件应具有:

      import { Subject } from 'rxjs';
      import { debounceTime, distinctUntilChanged } from 'rxjs/operators';
    
      @Output() inputChanged: EventEmitter<string> = new EventEmitter<string>();
      input = new Subject<string>();
    
      constructor() {
        this.input
            .pipe(debounceTime(300))
            .pipe(distinctUntilChanged())
            .subscribe(input => this.emitInputChanged(input));
      }
    
      onChange(input: string) {
         this.input.next(input);
      }
    

    这个 Subject 是可订阅的。您可以通过管道输入其他函数(如 debounce )然后可以在链的末端从中发出更改。我不知道你在用什么 ngModel 是的,但既然你的问题中有它,我就把它忘了。正在侦听 inputChanged 将在解抖动发生后获取更新的值。