繁体   English   中英

如何等待所有数据加载到Angular 2异步依赖的http调用中?

[英]How to wait till all data is loaded in Angular 2 async dependent http calls?

我正在研究一种处理从Jira中提取数据的工具。 我可以找到许多链接多个http调用的例子,使用前一个调用的数据一个接一个地进行。 但我偶然发现的是如何等待所有内部调用来解析和处理数据,然后才解决外部问题。

这里发生的事情是this.developmentService.getData(this.filter)方法不等待内部this.developmentService.getStoriesForEpic(epic.key)中每个史诗中故事的计数完成。是有问题的,因为在那之后我需要根据这些计数应用额外的过滤器。

updateChart() {
    this.loading = true;
    if (this.dataRequest) { this.dataRequest.unsubscribe(); }

  this.developmentService.getData(this.filter).toPromise().then(initiatives => {
    initiatives.map((initiative) => {
      initiative.devEpics.map((epic) => {
        return this.developmentService.getStoriesForEpic(epic.key).toPromise().then(stories => {
           Promise.all(stories.map((story) => {
            if (story.status == "To Do") {
              epic.storiesToDo++;
            }
            else if (story.status == "In Progress") {
              epic.storiesInProgress++;
            }
            else if (story.status == "Done") {
              epic.storiesDone++;
            }
          }))
        })
      })
  })
  this.data=initiatives;
})

我尝试了多种方法,但似乎无法实现。 任何帮助表示赞赏! 提前致谢

不要将它们转换为promises,并使用RXJS。

forkJoincombineLatest - 取决于您的预期行为。

https://rxjs-dev.firebaseapp.com/api/index/function/combineLatest

https://rxjs-dev.firebaseapp.com/api/index/function/forkJoin

你可以这样试试

async updateChart() {
    this.loading = true;
    if (this.dataRequest) { this.dataRequest.unsubscribe(); }

  this.developmentService.getData(this.filter).toPromise().then(initiatives => {
    initiatives.map((initiative) => {
      initiative.devEpics.map((epic) => {
       let dataFromGetStoriesForEpic = await getStoriesForEpic(epic);
        })
      })
  })
  this.data=initiatives;
})

这里我们为getStoriesForEpic创建一个函数

getStoriesForEpic(epic) {
return promise = new Promise ((resolve, reject) => {
this.developmentService.getStoriesForEpic(epic.key).toPromise().then(stories => {
           Promise.all(stories.map((story) => {
            if (story.status == "To Do") {
              epic.storiesToDo++;
            }
            else if (story.status == "In Progress") {
              epic.storiesInProgress++;
            }
            else if (story.status == "Done") {
              epic.storiesDone++;
            }
            resolve(epic);
      }))
  })   
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM