如何取消订阅 forkJoin 返回的 Observable?
How to unsubscribe from an Observable returned by forkJoin?
在我的 Angular2-typescript 应用程序中,我使用 forkJoin return Observable 只有在所有并行 HTTP 调用完成后。
问题:订阅回调一直无限期执行
这是我的代码:
http.service
import {Http} from "@angular/http";
constructor (private _http: HTTP) {}
makeGetRequest(....) {
return this._http.get(URL)
.map (res => res.json)
.toPromise();
my.service
import {Observable} from "rxjs/Observable";
import {HttpService} from "http.service"
constructor (private _httpService: HttpService) {}
myMethod(): Observable<any[]> {
return Observable.forkJoin(
this._httpService.makeGetRequest(
URL1
),
this._httpService.makeGetRequest(
URL2
)
)
}
my.component
import MyService from "my.service";
import Subscription from "rxjs";
constructor (private _service: MyService) {}
mySub: Subscription;
ngOnInit() {
this.mySub = this._service.myMethod.subscribe(data => {
data.forEach(console.log(data));
this.mySub.unsubscribe();
}
}
我尝试过的(同样的问题):
- return Http.service 中的 Observable 而不是 Promise
- 在 my.component 中使用 .first().subscribe() 而不仅仅是 subscribe()
- 放this.mySub.unsubscribe();在 ngOnInit 的末尾而不是在订阅回调中(也有 setTimeout(() => ....))
正如forkJoin
reference所说,它
Runs all observable sequences in parallel and collect their last elements.
这意味着运算符从已完成的可观察对象和 returns 具有单个值的已完成可观察对象中获取值。无需取消订阅。
您可以取消它。假设 observables
是您准备触发的一组 http 请求(通过 httpClient
执行)。
this.forkJoinSubscription = forkJoin(observables).subscribe(responses => {
. . . do something
});
this.forkJoinSubscription.unsubscribe();
您可能会在网络选项卡中注意到这些请求已被取消。
在我的 Angular2-typescript 应用程序中,我使用 forkJoin return Observable 只有在所有并行 HTTP 调用完成后。
问题:订阅回调一直无限期执行
这是我的代码:
http.service
import {Http} from "@angular/http";
constructor (private _http: HTTP) {}
makeGetRequest(....) {
return this._http.get(URL)
.map (res => res.json)
.toPromise();
my.service
import {Observable} from "rxjs/Observable";
import {HttpService} from "http.service"
constructor (private _httpService: HttpService) {}
myMethod(): Observable<any[]> {
return Observable.forkJoin(
this._httpService.makeGetRequest(
URL1
),
this._httpService.makeGetRequest(
URL2
)
)
}
my.component
import MyService from "my.service";
import Subscription from "rxjs";
constructor (private _service: MyService) {}
mySub: Subscription;
ngOnInit() {
this.mySub = this._service.myMethod.subscribe(data => {
data.forEach(console.log(data));
this.mySub.unsubscribe();
}
}
我尝试过的(同样的问题):
- return Http.service 中的 Observable 而不是 Promise
- 在 my.component 中使用 .first().subscribe() 而不仅仅是 subscribe()
- 放this.mySub.unsubscribe();在 ngOnInit 的末尾而不是在订阅回调中(也有 setTimeout(() => ....))
正如forkJoin
reference所说,它
Runs all observable sequences in parallel and collect their last elements.
这意味着运算符从已完成的可观察对象和 returns 具有单个值的已完成可观察对象中获取值。无需取消订阅。
您可以取消它。假设 observables
是您准备触发的一组 http 请求(通过 httpClient
执行)。
this.forkJoinSubscription = forkJoin(observables).subscribe(responses => {
. . . do something
});
this.forkJoinSubscription.unsubscribe();
您可能会在网络选项卡中注意到这些请求已被取消。