Angular 6 - rxjs 管道不适用于 valueChanges [英] Angular 6 - rxjs pipe not working on 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.我在我的代码中的其他地方对不同的 observable 使用了 pipe 方法,没有任何问题.
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.
推荐答案
您需要订阅
才能激活Observable
,
ngOnInit() {
this.filteredOptions = this.myControl.valueChanges
.pipe(
startWith(''),
map(val => this.filter(val))
).subscribe();
}
这篇关于Angular 6 - rxjs 管道不适用于 valueChanges的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!