【问题标题】:RxJS - Resolve multiple server callsRxJS - 解决多个服务器调用
【发布时间】:2017-09-11 14:28:07
【问题描述】:

我在 Angular 4 中使用 RxJS 来编写异步调用。

我需要调用服务器,获取响应并使用它进行另一个调用,获取此响应并使用它进行另一个调用等等。我为此使用下面的代码,这可以按预期工作

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 中,我需要打 2 个休息电话,并且只有在它们都解决后才继续。不仅如此,只有其中一个的响应会被传递到下一个 flatMap,因为另一个调用只会填充一个变量

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 调用也完成。

this.name = this.repoService.getDocProperties(this.objectId);

【问题讨论】:

标签: angular rxjs


【解决方案1】:

您可以将异步调用与 forkJoin 结合使用

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

this.myService.get('http://someotherurlhere');
this.myService.get('http://someurlhere');

它们可以这样组合:

let call1 = this.myService.get('http://someotherurlhere');
let call2 = this.myService.get('http://someurlhere');
return Observable.forkJoin([call1, call2])

当你订阅(或链接其他函数)加入的 observable 时,返回的数据将在一个数组中。因此,call1 的结果将位于索引 0 处,call2 位于索引 1 处。

Observable.forkJoin([call1, call2]).subscribe((results) => {
  results[0]; // call1
  results[1]; // call2
});

【讨论】:

  • 谢谢。那么,将传递给下一个 flatMap 的输出将是什么。我只需要将 call2(而不是 call1)的输出传递给下一个 flatMap
  • @kayasa 我编辑了答案,如果您需要更多说明,请告诉我
  • 如果我执行 Observable.forkJoin,则在此之后的下一个 flatMap 会引发错误 - 'Subscription' 类型上不存在“Property 'flatMap'。”
  • @kayasa 你包括订阅吗?如果你的链接,你不应该。例如:Observable.forkJoin(...).flatMap(...)...
猜你喜欢
  • 2018-04-07
  • 1970-01-01
  • 1970-01-01
  • 2014-05-22
  • 1970-01-01
  • 1970-01-01
  • 2021-12-29
  • 2021-01-04
  • 2019-10-23
相关资源
最近更新 更多