去抖动时间&角度6中的distingtUntilChanged [英] debounceTime & distinctUntilChanged in angular 6

查看:140
本文介绍了去抖动时间&角度6中的distingtUntilChanged的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在rxjs中找到了一些使用debounce和distinctUntilChanged的教程.如何在角度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)
      });
}

这篇关于去抖动时间&amp;角度6中的distingtUntilChanged的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆