问题描述
限时送ChatGPT账号..我在 rxjs 中找到了一些使用 debounce 和 distinctUntilChanged 的教程.我如何在 angular 6 中实现它?
I found some tutorial in rxjs that uses debounce and distinctUntilChanged. How can I implement it in angular 6?
教程代码是这样的:
var observable = Rx.Observable.fromEvent(input,'input');
observable.map(event=>event.target.value)
.debounceTime(2000)
.subscribe({
next:function(value){
console.log(value)
}
}
这是我的代码:
在 html 中,我有这个:
In html, I have this:
<input class="form-control" [(ngModel)]="userQuestion" type="text" name="userQuestion" id="userQuestions">
在打字稿中,我有这个:
in Typescript, I have this:
import { Subject,Observable } from "rxjs";
import { debounceTime,distinctUntilChanged } from "rxjs/operators";
ngOnInit() {
// initialization
this.userQuestion = new Observable;
this.userQuestion.pipe(
debounceTime(2000)).subscribe(val => {
console.log(val)
}
)
}
它不起作用.我怎样才能让它工作?
It doesnt work. How can I make it work?
推荐答案
需要注意的两件事:
在打字稿中,您没有正确初始化 Observable.如果您想基于 DOM 事件(例如 'input')生成 Observable,您应该使用 'fromEvent' 便捷方法
In the typescript you are not initialising your Observable properly. You should use the 'fromEvent' convenience method if you want to generate an Observable based on a DOM event (e.g. 'input')
其次,pipe
只是用来包裹任何操作符.因此不应在 pipe
Secondly, pipe
is just used to wrap around any operators. So a subscribe shouldn't be used within pipe
如果您使用@ViewChild,则必须在 ngAfterViewInit 中创建 Observable.在此之前将无法访问 ViewChild.
You must create the Observable in ngAfterViewInit if you're using @ViewChild. ViewChild won't be accessible before that point.
在您的模板中
<input #questionInput class="form-control" [(ngModel)]="userQuestion" type="text" name="userQuestion" id="userQuestions">
在 .ts 中
@ViewChild('questionInput') questionInput: ElementRef;
public input$: Observable<string>;
////
...code...
////
ngAfterViewInit() {
this.input$ = fromEvent(this.questionInput.nativeElement, 'input');
.pipe(
debounceTime(2000),
map((e: KeyboardEvent) => e.target['value'])
);
this.input$.subscribe((val: string) => {
console.log(val)
});
}
这篇关于去抖动时间 &角度 6 中的 distinctUntilChanged的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论