【问题标题】:How to call multiple http service in parallel from angular component如何从角度组件并行调用多个http服务
【发布时间】:2019-02-06 11:28:14
【问题描述】:

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

我有一个 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方法 因为我需要确保在编辑表单之前填写下拉列表

【问题讨论】:

  • 您是否尝试过添加回调()函数,以便在方法完成时调用回调()并且您知道方法1已完成

标签: angular


【解决方案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,只需将 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();
}

【讨论】:

  • zip 不是平行的,就像夹克上的拉链一样,一个接一个直到完成,combineLatestmergeforkJoin 是可以接受的替代方案。
  • 在 rxjs 5 中,使用 Observable.zip 进行并行调用。但是,我同意您对 rxjs6 的评论,这就是我使用 forkJoin 的原因
  • 请注意,this.fillform() 不会在任何 Observable 抛出错误时执行。来源:reactivex.io/documentation/operators/subscribe.html。无论有没有错误,你需要做的事情,你应该使用.finally()
猜你喜欢
  • 2023-03-20
  • 1970-01-01
  • 1970-01-01
  • 2018-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-03
相关资源
最近更新 更多