0

i want create search engine in my website. I want to use switchMap to cancel previous request, because this function run async.

I getting data from input by keyup, example:

<input type="text" (keyup)="subject.next($event.target.value)">

TypeScript

subject = new Subject<string>();

ngOnInit() {
this.subject.asObservable().pipe(debounceTime(500)).subscribe(res => {
  console.log(res);
});

}

I would like to use switchMap and timer here, but what will not change, it always does not work, does anyone have idea how to refactorize this code to work with switchMap and timer from RxJs?

My example in stackblitz:

https://stackblitz.com/edit/angular-playground-53grij?file=app%2Fapp.component.ts

Wojtar
  • 35
  • 3
  • `I want to use switchMap to cancel previous request` what previous request? You haven't shared what you've tried. – Reactgular Aug 15 '18 at 14:28

1 Answers1

2

You can try with something like this (assuming you are using RxJS 6):

subject = new Subject<string>();
subscription: Subscription;

ngOnInit() {
  this.subscription = this.subject
    .pipe(
      debounceTime(500),
      switchMap((query: string) => {
        return this.http.get('http://url?q=' + query);
      })
    )
    .subscribe((res: any) => {
      console.log(res);
    });
}

ngOnDestroy() {
  this.subscription.unsubscribe();
}
Jimmy Hedström
  • 561
  • 2
  • 10