去抖动时间 &角度 6 中的 distinctUntilChanged

编程入门 行业动态 更新时间:2024-10-23 22:35:32
本文介绍了去抖动时间 &角度 6 中的 distinctUntilChanged的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送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)
      });
}

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

更多推荐

[db:关键词]

本文发布于:2023-04-22 17:06:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1026886.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:角度   时间   amp   distinctUntilChanged

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!