gpt4 book ai didi

angular - Angular 6 中的 debounceTime 和 distinctUntilChanged

转载 作者:太空狗 更新时间:2023-10-29 18:29:00 31 4
gpt4 key购买 nike

我在 rxjs 中找到了一些使用 debounce 和 distinctUntilChanged 的​​教程。如何在 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 中,我有这个:

<input class="form-control" [(ngModel)]="userQuestion" type="text" name="userQuestion" id="userQuestions">

在 typescript 中,我有这个:

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)
}
)
}

它不起作用。我怎样才能让它发挥作用?

最佳答案

需要注意的两点:

在 typescript 中,您没有正确初始化 Observable。如果您想基于 DOM 事件(例如“input”)生成一个 Observable,您应该使用“fromEvent”便捷方法

其次,pipe 只是用来环绕任何运算符。因此,不应在 pipe

中使用订阅

编辑

如果您使用@ViewChild,则必须在 ngAfterViewInit 中创建 Observable。在此之前将无法访问 ViewChild。

在你的模板中

<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)
});
}

关于angular - Angular 6 中的 debounceTime 和 distinctUntilChanged,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51530169/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com