I am basically calling an API on keyup event of a textbox using switchmap. The problem that I am facing is that switchmap doesn't cancel the previous ongoing API call when a new API call is made
import {AfterViewInit, Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import {fromEvent, Observable} from "rxjs";
import {debounceTime, distinctUntilChanged, map, switchMap} from "rxjs/operators";
@Component({
selector: 'app-debounce-component',
templateUrl: './debounce-component.component.html',
styleUrls: ['./debounce-component.component.css']
})
export class DebounceComponentComponent implements OnInit,AfterViewInit {
constructor() { }
@ViewChild('searchinput') ele:ElementRef
ngOnInit(): void {
}
ngAfterViewInit(): void {
fromEvent(this.ele.nativeElement , 'keyup').pipe(
debounceTime(1000),
map(evt=>{
return evt['target']['value']
}),
switchMap(value=>{
console.log(value);
return this.createObservable(value);
}),
distinctUntilChanged()
).subscribe() ;
}
createObservable(value):Observable<any>{
return Observable.create(observer=>{
fetch(`http://localhost:3000/courses/${value}`).then(res=>{
res.json();
}).then(body=>{
observer.next(body);
observer.complete();
});
})
}
}
Even though it's now possible (it wasn't for a long time) to abort requests made with
fetch, you'll still need anAbortControllerto do so. Fortunately for us, RxJS has implemented an operator calledfromFetchthat handles this for us.Simply do
and it should work as you want!