angular 6 中的 debounceTime 和 distinctUntilChanged
debounceTime & distinctUntilChanged in angular 6
我在 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">
在打字稿中,我有这个:
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)
}
)
}
没用。我怎样才能让它发挥作用?
您需要注意两点:
在打字稿中,您没有正确初始化 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)
});
}
我在 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">
在打字稿中,我有这个:
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)
}
)
}
没用。我怎样才能让它发挥作用?
您需要注意两点:
在打字稿中,您没有正确初始化 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)
});
}