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?
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 withinpipe
EDIT
You must create the Observable in ngAfterViewInit if you're using @ViewChild. ViewChild won't be accessible before that point.
In your template
In .ts