首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >RxJS -解析多个服务器调用

RxJS -解析多个服务器调用
EN

Stack Overflow用户
提问于 2017-09-11 14:28:07
回答 1查看 885关注 0票数 2

我在角4中使用RxJS来组成异步调用。

我需要调用服务器,获取响应并使用它进行另一次调用,获取响应,并使用它进行另一次调用等等。我正在使用下面的代码进行此操作,此代码的工作原理与预期相同。

代码语言:javascript
代码运行次数:0
运行
复制
id;
name;
ngOnInit() {
    this.route.params
      .flatMap(
      (params: Params) => {
        this.id = params['id'];
        return this.myService.get('http://someurlhere');
      }
      )
      .flatMap(
      (response: Response) => {
        return this.myService.get('http://someurlhere');
      })
      .flatMap(
      (response: Response) => {
        return this.myService.get('http://someurlhere');
      })
      .subscribe(
      (response: Response) => {
        FileSaver.saveAs(blob, this.name );
      },
      (error) => {        
        console.log('Error ' + error)
      }
      )
  }

现在,我需要对它做些改变。在第一个flatMap中,我需要进行两个rest调用,只有当这两个调用都得到解决时才继续进行。不仅如此,其中之一的响应将传递到下一个flatMap,因为另一个调用只会填充一个变量。

代码语言:javascript
代码运行次数:0
运行
复制
id;
name;
ngOnInit() {
    this.route.params
      .flatMap(
      (params: Params) => {
        this.id = params['id'];
         // this is the 2nd REST call. It just populates a variable, so don't need the output to be passed to next flatMap. However, both the URLs in this section should resolve before the next flatMap is executed.
        this.name = this.myService.get('http://someotherurlhere');
        return this.myService.get('http://someurlhere');
      }
      )
      .flatMap(
      (response: Response) => {
        return this.myService.get('http://someurlhere');
      })
      .flatMap(
      (response: Response) => {
        return this.myService.get('http://someurlhere');
      })
      .subscribe(
      (response: Response) => {
        FileSaver.saveAs(blob, this.name );
      },
      (error) => {        
        console.log('Error ' + error)
      }
      )
  }

因此,我的问题是,应该如何编写这段代码,以便从服务器获得响应,但在移动到下一个平面图之前,等待其他rest调用也完成。

代码语言:javascript
代码运行次数:0
运行
复制
this.name = this.repoService.getDocProperties(this.objectId);
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-09-11 14:37:13

您可以将异步调用与forkJoin结合起来。

在您的情况下,您有两个电话:

代码语言:javascript
代码运行次数:0
运行
复制
this.myService.get('http://someotherurlhere');
this.myService.get('http://someurlhere');

它们可以这样组合在一起:

代码语言:javascript
代码运行次数:0
运行
复制
let call1 = this.myService.get('http://someotherurlhere');
let call2 = this.myService.get('http://someurlhere');
return Observable.forkJoin([call1, call2])

当您订阅(或链接其他函数)到可观察的连接时,返回的数据将位于数组中。因此,call1的结果将位于索引0,而call2将位于索引1。

代码语言:javascript
代码运行次数:0
运行
复制
Observable.forkJoin([call1, call2]).subscribe((results) => {
  results[0]; // call1
  results[1]; // call2
});
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46158118

复制
相关文章

相似问题

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