问题描述
如何取消4个或更多角度的未决HTTP请求.
How to cancel/abort all pending HTTP requests angular 4+.
有一个unsubscribe
方法可以取消HTTP请求,但是如何一次取消所有未决的请求.
There is an unsubscribe
method to cancel HTTP Requests but how to cancel all pending requests all at once.
特别是在路线更改时.
我做了一件事
ngOnDestroy() {
this.subscription.unsubscribe();
}
但是如何在全球范围内实现这一目标
but how to achieve this globally
有什么想法吗?
推荐答案
Checkout the takeUntil()
operator from RxJS to globally drop your subscriptions :
-RxJS 6+(使用pipe
语法)
- RxJS 6+ (using the pipe
syntax)
import { takeUntil } from 'rxjs/operators';
export class YourComponent {
protected ngUnsubscribe: Subject<void> = new Subject<void>();
[...]
public httpGet(): void {
this.http.get()
.pipe( takeUntil(this.ngUnsubscribe) )
.subscribe( (data) => { ... });
}
public ngOnDestroy(): void {
// This aborts all HTTP requests.
this.ngUnsubscribe.next();
// This completes the subject properlly.
this.ngUnsubscribe.complete();
}
}
-RxJS< 6
import 'rxjs/add/operator/takeUntil'
export class YourComponent {
protected ngUnsubscribe: Subject<void> = new Subject<void>();
[...]
public httpGet(): void {
this.http.get()
.takeUntil(this.ngUnsubscribe)
.subscribe( (data) => { ... })
}
public ngOnDestroy(): void {
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
}
}
基本上,每次要完成一堆流时,都可以使用next()
在取消订阅的Subject
上发出事件.取消订阅活动的Observable也是一个好习惯,因为该组件被破坏了,以避免内存泄漏.
You can basically emit an event on your unsubscribe Subject
using next()
everytime you want to complete a bunch of streams. It is also good practice to unsubscribe to active Observables as the component is destroyed, to avoid memory leaks.
值得一读:
这篇关于如何取消/取消订阅所有待处理的HTTP请求angular 4+的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!