5
在我的Angular2-typescript应用程序中,我使用forkJoin仅在所有并行HTTP调用完成后才返回Observable。如何取消订阅由forkJoin返回的Observable?
问题:认购回调一直被无限期执行
这里是我的代码:
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();
}
}
我试过(同样的问题):
- 返回一个可观察的Http.service而非my.component使用无极
- 。首先().subscribe()而不是只订阅()
- put this.mySub.unsubscribe();在ngOnInit的端部,而不是订阅回调内部(也用的setTimeout(()=> ....))
你的意思是'订阅回调持续无限期执行'? – Picci
这个问题没有意义。 forkJoin加入* completed * observables的结果,不应该取消订阅,因为它具有单个值。如果您在*无限期执行*时遇到问题,请提供一个[MCVE](http://stackoverflow.com/help/mcve),可以复制您的问题 – estus
@estus您是对的。显然这是因为订阅实例化了两次而导致了这个问题。随意回答这个问题,我会接受的;) – dragonmnl