如何从2个API调用中填充Observable <object []>

时间:2018-10-16 21:33:34

标签: angular reactjs

我需要返回一个Observable<MyResult[]>

要完成此操作,我需要进行2个单独的API调用以加载数据。

  1. 加载MyItem
  2. 为每个项目加载Gizmos []。

我问了类似的问题,但不同之处在于我将第二个API加载到第一个API的对象中。这次,我需要将两个API调用都加载到一个单独的对象中。

SO Question

export class MyItem{
  id: string;
  name: string;
};

export class Gizmo{
  id: string;
  itemId: string;
  name: string;
  color: string;
};

export class MyResult{
  item: MyItem;
  gizmos: Array<Gizmo>;
}

我已经阅读了React,但是仍然没有点击我在语法上无法/不能做的事情。

编辑:

我正在寻找以下结果:

{   
    "MyResult": [ 
        { "MyItem": { "id": "100", "name": "Bob", "Gizmo": [{"id": "1", "itemId": "100", "name": "Gizmo1", "color": "Red"}, { "id": "2", "itemId": "100", "name": "Gizmo2", "color": "Blue" } ] }}, 
        { "MyItem": { "id": "200", "name": "Sally", "Gizmo": [{ "id": "3", "itemId": "200", "name": "Gizmo3", "color": "Black" }, { "id": "4", "itemId": "200", "name": "Gizmo55", "color": "White" }] }}
    ]
}   

1 个答案:

答案 0 :(得分:0)

我已经在此stackblitz

中捕捉到了你想要的东西

检查浏览器控制台以查看结果。

这是主控制器代码:

import { Component } from '@angular/core';
import { Observable, of, combineLatest } from 'rxjs'
import { map } from 'rxjs/operators'
import { MyItem, Gizmo, MyResult } from './classes'

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {

  ngOnInit() {
    this.doApiCalls().subscribe((result: MyResult) => {
      console.log('result', result)
    })
  }

  doApiCalls(): Observable<MyResult> {
    // mimic an Observable response from an API
    const firstCall: Observable<MyItem> = of(new MyItem('100', 'fred'));

    // mimic an Observable response from an API
    const secondCall: Observable<Gizmo[]> = of([
      new Gizmo('1', '100', 'gizmo1', 'red'),
      new Gizmo('2', '100', 'gizmo2', 'blue')
    ]);

    const result: Observable<MyResult> = combineLatest(firstCall, secondCall).pipe(
      map(([item, gizmos]) => new MyResult(item, gizmos))
    )

    return result
  }
}