如何退订forkJoin返回的Observable? [英] How to unsubscribe from an Observable returned by forkJoin?
本文介绍了如何退订forkJoin返回的Observable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的Angular2-typescript应用程序中,我仅在进行所有并行HTTP调用后才使用forkJoin返回一个Observable.
In my Angular2-typescript app, I'm using forkJoin to return an Observable only once all the parallel HTTP calls were made.
问题:订阅回调将无限期执行
Issue: the subscription callback keeps being executed indefinitely
这是我的代码:
http.service
import {Http} from "@angular/http";
constructor (private _http: HTTP) {}
makeGetRequest(....) {
return this._http.get(URL)
.map (res => res.json)
.toPromise();
我的服务
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
)
)
}
我的组件
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();
}
}
我尝试过的(相同问题):
What I tried (same issue):
- 在Http.service中返回一个Observable而不是Promise
- 在my.component中使用.first().subscribe()而不是仅subscription()
- 放入this.mySub.unsubscribe();在ngOnInit的末尾而不是在订阅回调内部(也使用setTimeout(()=> ....))
推荐答案
查看全文