停止加载订阅

Stop loading in subscribe

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

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

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

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 运算符,正在进行的订阅将被取消(当作为参数传递给它的可观察对象发出时它取消订阅 - 完整的功能仍然运行).

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

常见的做法是在这种情况下使用 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);
  }