首页 > 解决方案 > 如何从角度组件并行调用多个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方法,因为我需要确保在编辑表单之前应该填写下拉列表

标签: angular

解决方案


您好,如果您使用的是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.zipforkJoin

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();
}

推荐阅读