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

4

1 回答 1

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();
}
于 2018-08-15T14:28:35.463 回答