相关疑难解决方法(0)

switchMap 和 debounceTime 取消挂起

我有一种方法可以根据搜索词搜索员工。

this._sub.pipe(
    debounceTime(500),
    filter(x => !!x),
    distinctUntilChanged(),
    switchMap(this.getResults.bind(this))
).subscribe((d: IDisplayEmp[]) => {
    console.log('RES', d)
    this.displayResults = d;
});

this._sub.next('mySearchTerm');
Run Code Online (Sandbox Code Playgroud)

这很有效,如果发出新的 API 调用,则会取消以前的 API 调用。然而问题来了。

活动 API 调用仅在发出去抖动时取消。如果在去抖动等待期间活动 API 调用返回,它仍会触发我的订阅。

我明白这是因为取消只发生在 switchmap 的范围内。

是否可以重构它,以便如果去抖动正在等待输入停止,它将取消任何挂起的 API 调用?

可能是一种天真的方法,但我尝试了类似下面的方法,它发出值,但现在没有去抖动效果。

this._sub.pipe(
    filter(x => !!x),
    distinctUntilChanged(),
    switchMap((x) => {
        return of(x)
            .pipe(
                debounceTime(500),
                this.getResults.bind(this)
            );
    })
).subscribe((d: IDisplayEmp[]) => {
    console.log('RES', d)
    this.displayResults = d;
});
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助。

observable rxjs typescript angular

2
推荐指数
2
解决办法
3789
查看次数

标签 统计

angular ×1

observable ×1

rxjs ×1

typescript ×1