服务检索数据后进行循环

时间:2018-11-13 19:23:58

标签: javascript angular

在尝试遵循Angular的标准时,我拆分了数据检索和其他视图逻辑。我创建了一个具有多个HTTP请求的服务,该请求在组件初始化时触发:

getData() {

    this.http.get(`https://example.com/corporate/Communications/_api/web/lists/getbytitle('Corporate Announcements')/items?$orderBy=PublishDate desc&$filter=(PublishDate le '${moment().format()}' and ExpirationDate ge '${moment().format()}' and OData__ModerationStatus eq '0' and ReadyToPublish eq 'Yes' and BannerArticle eq 'Yes' and BannerExpiration ge '${moment().format()}')`).subscribe(data => {
      console.log("bannerItems", data['value']);
      this.bannerItems = data['value'];
    });

    this.http.get(`https://example.com/corporate/Communications/_api/web/lists/getbytitle('Corporate Announcements')/items?$orderBy=PublishDate desc&$filter=(PublishDate le '${moment().format()}' and ExpirationDate ge '${moment().format()}' and OData__ModerationStatus eq '0' and ReadyToPublish eq 'Yes') and (BannerArticle eq 'No' or (BannerArticle eq 'Yes' and BannerExpiration le '${moment().format()}'))`).subscribe(data => {
      console.log("announcements", data['value']);
      this.announcements = data['value'];
    });

    this.http.get(`https://example.com/divisions/Risk/_api/web/lists/getbytitle('Corporate Announcements')/items?$orderBy=ID desc&$filter=(Expires ge '${moment().format()}' and OData__ModerationStatus eq '0')`).subscribe(data => {
      console.log("riskAnnouncements", data['value']);
      this.riskAnnouncements = data['value'];
    });

    this.http.get(`https://example.com/divisions/it/servicestatus/_api/web/lists/getbytitle('Service List')/items?$orderBy=Title asc&$filter=StatusKPI ne 'Service running normally'`).subscribe(data => {
      console.log("serviceAlerts", data['value']);
      this.serviceAlerts = data['value'];
    })

    this.http.get(`https://example.com/divisions/it/servicestatus/_api/web/lists/getbytitle('Service Event History')/items?$orderBy=Title asc&$filter=(Modified ge '${moment().subtract(30, 'days').format()}' and Status eq 'Information Alert')`).subscribe(data => {
      console.log("serviceInfoAlerts", data['value']);
      this.serviceInfoAlerts = data['value'];
    })

}

在我的组件中,我试图遍历serviceAlerts数组,但是,该循环在将数据分配给该数组之前触发。如何在不使用getData()的情况下让循环等到setTimeout全部完成后再触发?

1 个答案:

答案 0 :(得分:1)

首先,您服务中的getData()不返回任何内容。

如果您遵循角度编码标准,则将编写用于进行这些http调用的不同方法(分离和纯净代码)。例如:

getCodeData(){ return http.get("url").pipe(handleError())
getSecondCodeData(){ return http.get("Secondurl").pipe(handleError())

现在要解决从所有这些方法获取数据的问题: 您可以使用RxJS ForkJoin来达到这种效果:

Observable.forkJoin([
            this.myService.getCodeData(),
            this.myService.getSecondCodeData()
        ]).subscribe((results: any[]) => { 
        results[0] => will have the value from first http call and so on..
      })