Reputation: 2497
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.
Upvotes: 1
Views: 1887
Reputation: 889
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)
Upvotes: 2
Reputation: 19240
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?
Upvotes: 4