首页 文章

如何从角度组件并行调用多个http服务

提问于
浏览
0

如何在多次服务调用完成后才能从组件调用我的方法?

我有一个service.ts文件,它有一个方法可以根据密钥(即obj here)返回具有不同值的数组,如下所示: -

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方法,因为我需要确保在编辑表单之前应该填充下拉列表

1 回答

  • 1

    您好,如果您使用 rxjs 5 ,您可以使用Observable压缩:

    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 ,只需通过 forkJoin 更改 Observable.zip

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

相关问题