Reputation: 423
I doing search auto complete.
keypress(valueSearch){
// call Ajax search with ValueSearch
// ....
}
Each time keypress event, i want cancel old http request.
Upvotes: 2
Views: 2664
Reputation: 202176
In fact you need to rely on an observable created from the event. If you use the default event binding, you can't have access to this observable. There are opened issues regarding this problem:
Right now you need to reference the element with the @ViewChild
decorator and configure an observable on it:
@ViewChild('someElt')
someElt: ElementRef;
ngAfterViewInit() {
Observable.fromEvent(someElt.nativeElement, 'keyup');
}
Now you're able to leverage the switchMap
operator to like an HTTP request on it. If there is an in-progress request in the data flow, it will be canceled:
@ViewChild('someElt')
someElt: ElementRef;
ngAfterViewInit() {
Observable.fromEvent(someElt.nativeElement, 'keyup').switchMap((evt) => {
return this.http.get('something').map(res => res.json())
}).subscribe(data => {
// use data
});
}
Upvotes: 2