如何在 angular2 中进行连续的 http api 调用?

Posted

技术标签:

【中文标题】如何在 angular2 中进行连续的 http api 调用?【英文标题】:How to make sequential http api calls in angular2? 【发布时间】:2018-08-18 20:38:13 【问题描述】:

我有多个 api 调用,其中依赖于另一个调用。如何使用 rxjs 实现这一点?

【问题讨论】:

试试这个sample 【参考方案1】:
this.serviceInst.firstAPIMethod()
    .flatMap(firstMethodResult => this.serviceInst.secondAPIMethod(firstMethodResult))
    .flatMap(secondMethodResult => this.serviceInst.thirdAPIMethod(secondMethodResult))
    .subscribe(thirdMethodResult => 
          console.log(thirdMethodResult);
     );

【讨论】:

【参考方案2】:
let inSequence = (tasks) =>  // tasks being an array of functions returning promises
  return tasks.reduce((p, task) => p.then(task), Promise.resolve());


inSequence(tasks).then(() => 
  console.log('all requests done');
);

【讨论】:

以上是关于如何在 angular2 中进行连续的 http api 调用?的主要内容,如果未能解决你的问题,请参考以下文章