在我的 Angular2-typescript 应用程序中,我使用 forkJoin 仅在所有并行 HTTP 调用完成后返回一个 Observable。
问题:订阅回调一直无限期执行
这是我的代码:
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();
}
}
我试过的(同样的问题):
- 在 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.
这意味着运算符从已完成的可观察对象中获取值并返回具有单个值的已完成可观察对象。无需取消订阅。
关于angular - 如何取消订阅 forkJoin 返回的 Observable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40429666/