Angular 2个路由器参数发出多个http调用
Angular 2 router parameters issue multiple http calls
我在 Angular 中有一条路线,我通过 id
从我的数据库中加载一个元素。在我的组件中,我使用以下代码加载元素:
this.route.params
.map((params: Params) => params['id'])
.switchMap((id: number) => this.service.getElement(id))
.catch((e) => {
return Observable.throw(e);
})
.subscribe((data: Models.IElement) => {
this.element= data as Models.IElement;
this.setTitle();
}, () => this.router.navigate(['/']));
其中 this.service.getElement(id)
进行 http 调用,returns 进行 Observable。一切顺利。我现在遇到的问题是我想发出第二个 http 调用,但我不知道在哪里添加第二个服务 http 调用的代码(这将是与 getElement
类似的方法,接收 id
作为参数)。
更多信息: 第二个 http 调用最好与 getElement
调用并行发出。它仅取决于 Params
中的 id
。
如何使用 Observables 完成这项工作?有什么办法让它起作用吗?
根据@Maxime 的评论,我得到了以下代码:
this.route.params
.map((params: Params) => params['id'])
.switchMap((id: number) => {
this.id = id;
return Observable.forkJoin([this.service.getElem(id), this.service.getElemDocs(id)]);
})
.catch((e) => {
return Observable.throw(e);
})
.subscribe(([elem, documents]) => {
this.elem= elemas Models.IElement;
this.elemDocuments = documents;
this.setTitle();
}, () => this.router.navigate(['/']));
这会同时启动两个调用并等待它们完成。
我在 Angular 中有一条路线,我通过 id
从我的数据库中加载一个元素。在我的组件中,我使用以下代码加载元素:
this.route.params
.map((params: Params) => params['id'])
.switchMap((id: number) => this.service.getElement(id))
.catch((e) => {
return Observable.throw(e);
})
.subscribe((data: Models.IElement) => {
this.element= data as Models.IElement;
this.setTitle();
}, () => this.router.navigate(['/']));
其中 this.service.getElement(id)
进行 http 调用,returns 进行 Observable。一切顺利。我现在遇到的问题是我想发出第二个 http 调用,但我不知道在哪里添加第二个服务 http 调用的代码(这将是与 getElement
类似的方法,接收 id
作为参数)。
更多信息: 第二个 http 调用最好与 getElement
调用并行发出。它仅取决于 Params
中的 id
。
如何使用 Observables 完成这项工作?有什么办法让它起作用吗?
根据@Maxime 的评论,我得到了以下代码:
this.route.params
.map((params: Params) => params['id'])
.switchMap((id: number) => {
this.id = id;
return Observable.forkJoin([this.service.getElem(id), this.service.getElemDocs(id)]);
})
.catch((e) => {
return Observable.throw(e);
})
.subscribe(([elem, documents]) => {
this.elem= elemas Models.IElement;
this.elemDocuments = documents;
this.setTitle();
}, () => this.router.navigate(['/']));
这会同时启动两个调用并等待它们完成。