首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在Angular2中调用多个相关的Http调用

在Angular2中调用多个相关的Http调用
EN

Stack Overflow用户
提问于 2017-02-27 20:23:55
回答 5查看 1.2K关注 0票数 0

我在我的应用程序中有四个HTTP调用(在单击按钮之后),其中第四个调用依赖于上述三个调用。我希望第四个调用等待并从所有三个调用中获取数据。(我从三次调用中获得的数据需要作为输入发送到第四次调用)

代码语言:javascript
运行
复制
LoadDetails() {
    this.DataService.M1().subscribe((Model1: Project.Models.Model1[]) => {
        this.SomeData1 = Model1;
    });
    this.DataService.M2().subscribe((Model2: Project.Models.Model2[]) => {
        this.SomeData2 = Model2;
    });
    this.DataService.M3().subscribe((Model3: Project.Models.Model3[]) => {
        this.SomeData3 = Model3;
    });
    this.DataService.M4(this.SomeData1.Id, this.SomeData2.Id, this.SomeData3.Id).subscribe((Model4: Project.Models.Model4[]) => {
        this.SomeData4 = Model4;
    });
}

如何让第四个呼叫等待上述三个呼叫完成?

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2017-02-27 20:37:44

这应该能帮到你:

代码语言:javascript
运行
复制
LoadDetails() {
    Observable.forkJoin([this.DataService.M1(), this.DataService.M2(), this.DataService.M3()]).mergeMap((datas:any[]) => {
        this.SomeData1 = data[0];
        this.SomeData2 = data[1];
        this.SomeData3 = data[2];

        //Here you can do whatever you want, bevor you request SomeData4
        return this.DataService.M4(this.SomeData1.Id, this.SomeData2.Id, this.SomeData3.Id);
    }).subscribe((Model4: Project.Models.Model4[]) => {
        this.SomeData4 = Model4;
    });
}

这将同时请求SomeData1-3,如果所有数据都存在,它将请求SomeDate4

注意:

如果不加载所有RxJS运算符,则必须添加以下导入:

代码语言:javascript
运行
复制
import 'rxjs/add/operator/mergeMap';
import 'rxjs/add/observable/forkJoin';
票数 1
EN

Stack Overflow用户

发布于 2017-02-27 21:33:43

您可以使用区域概念来处理此类操作。Zone.js

代码语言:javascript
运行
复制
let LoadDetailsZone = Zone.current.fork({
  name: 'detailZone',
  onHasTask() {
    this.DataService.M4(this.SomeData1.Id, this.SomeData2.Id, this.SomeData3.Id).subscribe((Model4: Project.Models.Model4[]) => {
          this.SomeData4 = Model4;
      });
  }
})
LoadDetailsZone.run(() => {
  this.DataService.M1().subscribe((Model1: Project.Models.Model1[]) => {
      this.SomeData1 = Model1;
  });
  this.DataService.M2().subscribe((Model2: Project.Models.Model2[]) => {
      this.SomeData2 = Model2;
  });
  this.DataService.M3().subscribe((Model3: Project.Models.Model3[]) => {
      this.SomeData3 = Model3;
  });
})

您可以使用onHasTask函数定义一个区域,该函数在zone.run()中的所有调用之后调用。

票数 1
EN

Stack Overflow用户

发布于 2017-02-27 20:26:31

代码语言:javascript
运行
复制
this._villageService.GetAllVillages()
    .flatMap(
       (response) => {
         // take from the response what you want and use it for the next call
         this._villageService.GetAllWorkAreas(//pass the thing from your previous response here)
       }
    )
    .flatMap(
      ....
    )
    .subscribe(...)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42485769

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档