In the component you can do somthing like this. Create RxJS Subject
, In search
method which is called on keyup
event, do .next()
on this Subject
you have created. Then subscribe
in ngOnInit()
will debounce
for 1 second, as in below code.
searchTextChanged = new Subject<string>();
constructor(private http:Http) {
}
ngOnInit(): void {
this.subscription = this.searchTextChanged
.debounceTime(1000)
.distinctUntilChanged()
.mergeMap(search => this.getValues())
.subscribe(() => { });
}
getValues() {
return this.http.get("https://www.example.com/search/?q="+this.q)
.map(
(res:Response) => {
const studentResult = res.json();
console.log(studentResult);
if(studentResult.success) {
this.results = studentResult.data;
} else {
this.results = [];
}
}
)
}
search($event) {
this.searchTextChanged.next($event.target.value);
}
rxjs v6 has several breaking changes including simplifying import points for operators. Try installing rxjs-compat
, which adds back those import paths until the code has been migrated.
Import the necessary operators from RxJS
. Below ones are for RxJS 5.x
import { Subject } from "rxjs/Subject";
import "rxjs/add/operator/debounceTime";
import "rxjs/add/operator/distinctUntilChanged";
import { Observable } from "rxjs/Observable";
import "rxjs/add/operator/mergeMap";