【问题标题】:Angular 6 - rxjs pipe not working on valueChangesAngular 6 - rxjs 管道不适用于 valueChanges
【发布时间】:2018-11-03 12:52:57
【问题描述】:

我有一个反应式表单,带有文本输入。为了便于在我的打字稿中访问,我声明:

get parentId(): FormControl {
    return this.addForm.get("parentId") as FormControl;
}

这部分工作正常,控件被正确访问。

如果我这样做,现在在我的 ngOnInit 中:

this.parentId.valueChanges.subscribe(() => console.log("Changed"));

正如预期的那样,在输入中每个更改的字符处都会执行控制台日志。但如果我这样做:

this.parentId.valueChanges.pipe(tap(() => console.log("Changed")));

什么都没有发生。没有错误,什么都没有。我也尝试使用 map、switchMap 等。没有任何效果。似乎管道不适用于 valueChanges。我在我的代码的其他地方在不同的可观察对象上使用管道方法没有任何问题。

而且我需要在这里使用管道来去抖动、映射等。

知道我做错了什么吗?

-- 编辑--

这是来自 Angular Material 网站的代码示例,位于自动完成组件上:

ngOnInit() {
   this.filteredOptions = this.myControl.valueChanges
       .pipe(
          startWith(''),
          map(val => this.filter(val))
       );
}

最后没有订阅,示例有效。

【问题讨论】:

  • Observables 在您订阅它们之前不会发出任何东西。所以如果你想看到tap的输出,你需要在pipe()之后调用subscribe()
  • 你需要在链的末尾有一个subscribe() 来激活 observable。
  • 在 Angular Material 网站上自动完成组件的示例中没有这样的东西:
  • 你说得对。示例中没有订阅,因为管道绑定到使用异步管道“订阅”的变量。我的错不明白这一点。谢谢。
  • @martin 刚来找同样的问题,非常感谢!

标签: angular rxjs observable angular6


【解决方案1】:

你需要subscribe激活Observable

ngOnInit() {
   this.filteredOptions = this.myControl.valueChanges
       .pipe(
          startWith(''),
          map(val => this.filter(val))
       ).subscribe();
}

【讨论】:

  • 如此简单,却又如此准确。谢谢。我仍在努力理解可观察对象及其与承诺的差异。
  • 您也可以在模板中使用管道异步。 *ngFor="let 过滤选项的选项 | async"
猜你喜欢
  • 2020-09-26
  • 1970-01-01
  • 1970-01-01
  • 2020-06-18
  • 2020-07-27
  • 2020-03-26
  • 2018-05-27
  • 1970-01-01
  • 2018-02-14
相关资源
最近更新 更多