如何从一个叫做回调函数在RxJS switchMap退订?

问题描述 投票:0回答:1

我有角及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。

问题是,当我们调用退订我们的自动提示列表订阅(以组件destroy生命周期):

this.autosuggestlistSubscription.unsubscribe();

该认购的部分不叫,所以自动提示已经不运行。但myBackendRequestFunction仍称在switchMap(我们看到开发工具网络标签发射的请求)。因此,我们的退订只能用于认购的部分。

我怎样才能确保整个结构是退订,并不再叫什么名字?

angular rxjs
1个回答
0
投票

若输入值已更改内部认购应该被取消。也许代码将是一点点清洁是这样的:

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>

这样,您就不必在所有退订。

© www.soinside.com 2019 - 2024. All rights reserved.