停止加载订阅

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

如果必须加重负载,最好的方法是什么。我有以下内容。

loadProducts() {
    this.subscription = this._productService.getAll()
      .subscribe(products => {
        this.isLoading = false
        this.products = products;
      },
        () => this.isLoading = false,
        () => this.isLoading = false
      );
  }

this.isLoading = false在“ next”,“ error”和“ complete”中显然是为了确保即使出现错误也停止加载。可以说有一种方法可以减少这种情况,例如将回调或lambda附加到订阅并在所有情况下都运行]

javascript angular typescript rxjs reactivex
2个回答
0
投票

[通常的做法是在这种情况下使用RxJS运算符,例如finalizetapcatchError

loadProducts() {
    this.subscription = this._productService.getAll()
      .pipe(
          finalize(() => (this.isLoading = false)),
          catchError(error => {
            this.isLoading = false;
            return throwError(error);
          })
        )
      .subscribe(products => this.products = products);
  }

0
投票

Stackblitz demo

您可以执行以下操作:

_cancel$ = new Subject<void>();

loadProducts() {
  this.subscription = this._productService.getAll()
    .pipe(takeUntil(this._cancel$))
    .subscribe(products => (this.products = products),
    () => this.isLoading = false,
    () => this.isLoading = false
  );
}

例如,您可以这样做:

<button (click)="loadProducts()">Load Products</button>
<button (click)="_cancel$.next()">Cancel Loading Products</button>

_cancel$发出时,正在进行的订阅将由于takeUntil运算符而被取消(当作为参数传递给它的observable发出时,它取消订阅-完整功能仍在运行。

不需要在订阅者函数中将isLoading设置为false,因为您已经在错误函数和完整函数上进行了此操作。

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