我想在我的网站上创建搜索引擎。我想用switchMap来取消之前的请求,因为这个函数是异步运行的。
我通过keyup从输入中获取数据,例如:
<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);
});}
我想在这里使用switchMap和timer,但是什么都不会改变,它总是不起作用,有人知道如何重构这段代码来使用RxJ中的switchMap和timer吗?
我在stackblitz中的例子:
https://stackblitz.com/edit/angular-playground-53grij?file=app%2Fapp.component.ts
发布于 2018-08-15 22:28:35
您可以尝试如下所示(假设您使用的是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();
}https://stackoverflow.com/questions/51860416
复制相似问题