debounceTime & distinctUntilChanged in angular 6

2020-07-22 17:58发布

I found some tutorial in rxjs that uses debounce and distinctUntilChanged. How can I implement it in angular 6?

The tutorial code is this:

var observable = Rx.Observable.fromEvent(input,'input');

observable.map(event=>event.target.value)
    .debounceTime(2000)
    .subscribe({
        next:function(value){
        console.log(value)
    }
}

This is my code:

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?

1条回答
虎瘦雄心在
2楼-- · 2020-07-22 18:27

Two things you need to be mindful of:

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

Secondly, pipe is just used to wrap around any operators. So a subscribe shouldn't be used within pipe

EDIT

You must create the Observable in ngAfterViewInit if you're using @ViewChild. ViewChild won't be accessible before that point.

In your template

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

In .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)
      });
}
查看更多
登录 后发表回答