angular - 如何从角度组件并行调用多个http服务
问题描述
只有在多个服务调用完成后,如何才能从组件调用我的方法?
我有一个 service.ts 文件,它具有一种方法,该方法将根据键(即此处的 obj)返回具有不同值的数组,如下所示:-
getdata(type:numer)
{
// make a post call to get the data
}
在这里,在 component.ts 文件中,我有两个方法将调用上述服务方法,如下所示:- 这两个方法用于在单击编辑表单按钮时填充 html 中的下拉列表
method1()
{
this.service.getdata().subscribe((res: any) => {
data1 = res;
});
}
method2()
{
this.service.getdata().subscribe((res: any) => {
data2 = res;
});
}
我还有另一种方法可以在编辑点击时填写表单数据
fillForm()
{
// do something
}
现在,我的要求是我需要在component.ts中调用method1和method2,并且我需要在完成上述两个方法后调用这个fillForm方法,因为我需要确保在编辑表单之前应该填写下拉列表
解决方案
您好,如果您使用的是rxjs 5,您可以使用 Observable zipping :
Observable.zip(
this.method1(),
this.method2()
).subscribe(
([dataFromMethod1, dataFromMethod2]) => {
// do things
},
(error) => console.error(error),
() => {
// do things when all subscribes are finished
this.fillform();
}
)
使用rxjs 6,只需更改Observable.zip
:forkJoin
forkJoin(
this.method1(),
this.method2()
).subscribe(
([dataFromMethod1, dataFromMethod2]) => {
// do things
},
(error) => console.error(error),
() => {
// do things when all subscribes are finished
this.fillform();
}
)
您需要更改方法以返回 Observables :
method1()
{
return this.service.getdata();
}
method2()
{
return this.service.getdata();
}
推荐阅读
- html - 如何在没有页面或帖子 ID 的情况下使用 :not() ?
- spartacus-storefront - 升级到后来的 Spartacus 次要版本或补丁版本是否安全,即从 3.2.2 升级到 3.3.0?
- java - 无法使用 selenium Java 调用对 TestNG 测试用例执行鼠标操作的方法
- python - 无法将字符串转换为浮点数(将图像文件读取为字节)
- python - 如何加载预训练的 pytorch 权重
- sql-server - sqlpackage.exe - 错误 SQL72014:.Net SqlClient 数据提供程序:未找到 Windows NT 用户或组
- html - 带有粘性菜单的仅 CSS 视差滚动
- python - 有限 HMM 及其 Digamma 矩阵
- file - Micrium 文件系统分区问题
- reactjs - 当我们将 Redux 与 React 一起使用时,我们是否将所有状态都放入 Redux 中?