3

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?

Ignacio Ara
  • 2,476
  • 2
  • 26
  • 37
Jemuel Elimanco
  • 416
  • 2
  • 4
  • 20

1 Answers1

2

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)
      });
}
Rich
  • 882
  • 1
  • 8
  • 19
  • There are errors. first, in variable this.input$, the error is Type 'Subscription' is not assignable to type 'Observable' Property '_isScalar' is missing in type 'Subscription'. Second. questionInput does not exist on type TestingComponent – Jemuel Elimanco Jul 26 '18 at 07:19
  • I've edited my answer to correctly assign inuput$. Make sure that you have added the template reference in your HTML in order for the ElementRef to be found – Rich Jul 26 '18 at 07:23