我在Angular&RxJS中有以下autosuggestlist结构:
this.autosuggestlistSubscription = this.input.valueChanges
.pipe(
debounceTime(500),
distinctUntilChanged(),
switchMap((value: string) => {
return this.myBackendRequestFunction(value).pipe(catchError(err => {
this.errorFn(err);
return EMPTY;
}));
})
)
.subscribe((suggestlist: Array<OptionItem>) => {
// go on with the suggestlist ...
});
我们注册自己输入字段中的更改。每次我们输入这个字段时,管道就会开始工作。由于我们想在用户键入下一个请求后立即取消上一个请求,因此我们使用 switchMap。
问题是,当我们调用自动建议列表订阅的取消订阅时(在组件的销毁生命周期中(:
this.autosuggestlistSubscription.unsubscribe();
不会调用订阅部分,因此自动建议不再运行。但是 myBackendRequestFunction 仍然在 switchMap 中被调用(我们看到请求在开发人员工具网络选项卡中触发(。因此,我们的退订仅适用于订阅部分。
如何确保取消订阅整个构造并且不再调用?
如果输入值已更改,则应取消内部订阅。也许这样代码会更干净一些:
this.autosuggestlistSubscription = this.input.valueChanges
.pipe(
distinctUntilChanged(),
debounceTime(500),
switchMap((value: string) => this.myBackendRequestFunction(value),
catchError(err => {
this.errorFn(err);
return EMPTY;
})
.subscribe((suggestlist: Array<OptionItem>) => {
// go on with the suggestlist ...
});
你甚至可以使用(没有订阅(((:
this.autosuggestlist$ = this.input.valueChanges.pipe(... pipes from fist code block...);
在你的 HTML 中带有这样的东西:
<ul>
<li *ngFor="let item of autosuggestlist$ | async">{{item.fooPropertyName}}</li>
</ul>
这样,您就不必取消订阅。