I need to wait for the result of 2 AJAX requests to make some calculation on it.
I have found the Observable.forkJoin
method that seems to do the job. So in my component I've added :
import { Observable } from 'rxjs/Rx';
// ...
ngOnInit() {
Observable.forkJoin(
this.instrumentService.current,
this.tuningService.tunings
).subscribe(
data => {
console.log(data);
}
);
}
The AJAX requests are sent but I never pass in the subscribe
callback.
If I try to execute each request separatly it works fine :
this.instrumentService.current.subscribe(instrument => {
console.log(instrument);
this.instrument = instrument;
});
this.tuningService.tunings.subscribe(tunings => {
console.log(tunings);
this.tunings = tunings;
});
In the data services ( instrumentService
and tuningService
), the Observable
are declared like this (maybe the source of the bug, don't know) :
private _tunings: BehaviorSubject<Tuning[]> = new BehaviorSubject([]);
/**
* Class constructor.
*
* @param {ApiService} apiService
*/
constructor (private apiService: ApiService) {
this.getAll().subscribe(tunings => this._tunings.next(tunings));
}
public get tunings() {
return this._tunings.asObservable();
}
public getAll(): Observable<Tuning[]> {
return this.apiService.call(this.url);
}
The apiService
is responsible of calling the built-in angular http
service.
As far as i remember forkJoin
currently has a bug, if one of the Observable
returns null
then the forkJoin
subscription is never called. Can you try with .zip
instead?
For me, the combineLatest
rxjs operator turned out to be the one I was looking for. It works with BehaviorSubjects the way you probably expected forkJoin
to work:
When any observable emits a value, emit the last emitted value from each.
(Documentation: https://www.learnrxjs.io/learn-rxjs/operators/combination/combinelatest )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.