在我的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();
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而不是Promise中返回一个Observable
>在my.component中使用.first().subscribe()而不是subscribe()
>把this.mySub.unsubscribe();在ngOnInit的末尾而不是在subscribe回调中(也使用setTimeout(()=> ….))
正如
forkJoin
reference所说,它
Runs all observable sequences in parallel and collect their last elements.
这意味着运算符从已完成的observable中获取值,并返回具有单个值的已完成的observable.没有必要取消订阅.