In my Angular component ngOnInit() I want to:
Both HTTP calls are always executing, but when my first observable is wired up to route.params, the forkJoin(...).subscribe(...) method never runs. If I replace this.route.params with Observable.of({id: 1234}) forkJoin().subscribe() gets called properly.
// VERSION 1 forkJoin().subscribe() never gets called
var dependentObservable = this.route.params
.switchMap(params => {
this.myId = +params['id'];
return this.myService.getMyInfo(this.myId);
});
// VERSION 2 forkJoin().subscribe gets called
var dependentObservable = Observable.of({id: 123})
.switchMap(params => {
this.myId = +params['id'];
return this.myService.getMyInfo(this.myId);
});
var independentObservable = this.myService.getOtherInfo();
Observable.forkJoin([dependentObservable, independentObservable])
.subscribe(
results = { ... },
error => { ... },
() => { ... }
);
My guess is route.params is never completed. That's why forkJoin does not work. You can use combineLatest instead of forkJoin
According to this doc forkJoin emit the last value from each observables, when all observables completed.
Observable.of({id: 123})
will be compleated immediately after giving {id: 123}
But
this.route.params
Will never be completed. Since route params can be changed by a user when he edits browser address bar. This changes will be never stopped.
I think you can complete observable using take(1):
this.route.params.take(1)
Or, If you want to be responsive to changing of route params use combineLatest
Observable.combineLatest(dependentObservable, independentObservable)