【发布时间】:2017-03-10 19:37:32
【问题描述】:
在我的 Angular 组件 ngOnInit() 我想:
- 读取路由参数并使用它作为参数执行依赖 HTTP 调用。
- 执行单独的 HTTP 调用。
- 等待两个 HTTP 调用完成。
两个 HTTP 调用总是在执行,但是当我的第一个 observable 连接到 route.params 时,forkJoin(...).subscribe(...) 方法永远不会运行。如果我用Observable.of({id: 1234}) 替换this.route.params forkJoin().subscribe() 会被正确调用。
// 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 => { ... },
() => { ... }
);
【问题讨论】: