在我的 Angular2-typescript 应用程序中,只有在所有并行 HTTP 调用完成后,我才使用 forkJoin 返回 Observable。
Issue:订阅回调无限期地持续执行
这是我的代码:
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 的末尾而不是在 subscribe 回调中(也使用 setTimeout(() => ....))
As forkJoin参考 https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/forkjoin.md说,它
并行运行所有可观察序列并收集它们的最后元素。
这意味着该运算符从已完成的可观察量中获取值,并返回具有单个值的已完成可观察量。无需取消订阅。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)