【问题标题】:Stop loading in subscribe停止加载订阅
【发布时间】:2020-05-20 23:08:24
【问题描述】:
如果我必须加载,最好的方法是什么。
我有以下。
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 附加到订阅并让它在所有情况下运行
【问题讨论】:
标签:
javascript
angular
typescript
rxjs
reactivex
【解决方案1】:
一种常见的做法是在这种情况下使用 RxJS 运算符,例如 finalize 或 tap 和 catchError:
loadProducts() {
this.subscription = this._productService.getAll()
.pipe(
finalize(() => (this.isLoading = false)),
catchError(error => {
this.isLoading = false;
return throwError(error);
})
)
.subscribe(products => this.products = products);
}
【解决方案2】:
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,因为您已经在错误函数和完整函数上进行了设置。