[英]RxJs and switchMap
我想在我的網站上創建搜索引擎。 我想使用switchMap取消先前的請求,因為此函數異步運行。
我通過鍵盤輸入從輸入中獲取數據,例如:
<input type="text" (keyup)="subject.next($event.target.value)">
打字稿
subject = new Subject<string>();
ngOnInit() {
this.subject.asObservable().pipe(debounceTime(500)).subscribe(res => {
console.log(res);
});
}
我想在這里使用switchMap和timer,但是什么都不會改變,它始終不起作用,沒有人知道如何重構此代碼以與RxJs的switchMap和timer一起使用嗎?
我在stackblitz中的示例:
https://stackblitz.com/edit/angular-playground-53grij?file=app%2Fapp.component.ts
您可以嘗試使用以下方法(假設您正在使用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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.