rxjs管道不适用于valueChanges

rxjs管道不适用于valueChanges

本文介绍了Angular 6-rxjs管道不适用于valueChanges的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a reactive form, with a text input. For ease of access in my typescript, I declared:

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

这部分有效,可以正确访问控件.

This part works, the control is properly accessed.

如果执行此操作,现在在我的ngOnInit中:

Now in my ngOnInit if I do this:

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

按预期,对输入中每个更改的字符执行控制台日志.但是,如果我这样做:

The console log is executed at every character changed in the input, as expected. But if I do this:

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

什么都没发生.没有错误,没有任何东西.我也尝试过使用map,switchMap等.似乎该管道无法在valueChanges上运行.我在代码的其他地方对不同的可观察对象使用了管道方法,没有任何问题.

Nothing happens. No errors, no anything. I tried also using map, switchMap, etc.nothing works. It seems that the pipe does not work on valueChanges. I am using the pipe method elsewhere in my code on different observables without any problem.

我需要在此处使用管道,以进行反跳,映射等操作.

And I need to use pipe here in order to debounce, map, etc.

知道我在做什么错吗?

-编辑-

这是Angular Material网站上自动完成"组件上的代码示例:

This is the code example from Angular Material site, on Autocomplete component:

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

最后没有订阅,该示例有效.

There is no subscribe at the end and the example works.

推荐答案

您需要订阅才能激活可观察者,

You need to subsrcibe to activate the obserable,

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

这篇关于Angular 6-rxjs管道不适用于valueChanges的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-10 23:29