具有3个或更多REST调用的Angular 2报告

时间:2017-02-02 22:11:53

标签: rest http angular

我正在尝试创建一个自定义报告/页面,该报告/页面是通过拉入三个不同的表 - 订单标题,订单明细和作业单来构建的。我可以通过常规javascript(处理所有REST调用然后生成HTML代码以插入DOM)来使其正常工作但我无法弄清楚Angular 2中的方法应该是什么。表依赖项是Order Header - >订单明细 - >工作单。我有三个服务,每个REST调用链接一个(参见下面的代码)。我正在努力解决如何使所有三个表中的数据正确显示在HTML模板上,其中Order Header信息在一行上,每个订单头下面的子细节行。

我在app.component中试过类似的东西:

this.ordersService.getOrders()
     .subscribe(data => {
        this.orders = data;
    for (let i in this.orders) {

    this.detailsService.getDetails(this.orders[i].id)
        .subscribe(data => {
              this.details = data;

              for (let ii in this.details) {
                  this.jobTicketService.getJobTicket(this.orders[i].id, this.details[ii].id)
                              .subscribe(data => {
                                      // process data
                                   }

app.component.html - (未格式化为最终形式,仅用于测试)

<div id="title">
    {{title}}
</div>
<div *ngFor="let order of orders">
    {{order.Title}}
    <div *ngFor="let detail of details">
        {{detail.Description}}
        <div *ngFor="let jobTicket of jobTickets">
            {{activity.Title}}
        </div>
    </div>
</div>

我得到的是:

Order 1
    Order 4 Detail Id 5          (last record in details array)
        Job Ticket Order 4 Detail Id 5 Activity 1
        Job Ticket Order 4 Detail Id 5 Activity 2
Order 2
    Order 4 Detail Id 5          (last record in details array)
        Job Ticket Order 4 Detail Id 5 Activity 1
        Job Ticket Order 4 Detail Id 5 Activity 2
Order 3
    Order 4 Detail Id 5          (last record in details array)
        Job Ticket Order 4 Detail Id 5 Activity 1
        Job Ticket Order 4 Detail Id 5 Activity 2
Order 4
    Order 4 Detail Id 5
        Job Ticket Order 4 Detail Id 5 Activity 1
        Job Ticket Order 4 Detail Id 5 Activity 2

我可以告诉我在向console.log输出值时获取数据,但似乎并不了解如何将其正确链接到模板。

以下是我最终需要它的示例:

订单:1描述:定制产品客户:ABC公司

  Item: Product123       Qty. 3       Production Status: In Shipping

订单:2描述:特别订单客户:ACME公司

  Item: Product234       Qty. 1       Production Status: In Production
  Item: Product123       Qty. 3       Production Status: In Shipping

提前致谢!

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:

public get data$() {
   return this.ordersService.getOrders()
     .switchMap(orders => Observable
        .forkJoin(...orders.map(order => this.detailsService.getDetails(order.id))
          .mergeMap(([...details]) => Observable
            .forkJoin(details.map(detail => this.jobTicketService.getJobTicket(detail.id))
              .mergeMap(([...tickets]) => {orders, details, tickets})
            )
          )
        )
     );
}

如果您使用以下内容订阅:

this.data$.subscribe(data => {
  // process your data (should be { orders: orders, details: details, tickets: tickets})
})

注意:刚刚完成,未经测试

在您的模板中,您可以使用它(示例):

<div *ngFor="let order of (data$ | async)?.orders)>your order</div>