如何在Angular / RxJS中合并两个可观察对象?

问题描述

在我的服务中,我有以下方法

  getMap(): any {
    return this.http.get(`someURL`);
  }

  getAssets(): any {
    return this.http.get(`someURL`);
  }

在我的组件中,我像这样使用它们:

  ngOnInit() {
    this.myService.getMap().subscribe(data => {
      this.map = data; // Returns ["map-1.svg","map-0.svg"]
    });

    this.systemMapService.getAssets().subscribe(data =>  {
        this.assets = data; // Returns ["map-mapping-0.json","map-mapping-1.json"]
    });
  }

在我的模板中,我想像这样使用它:

<mat-tab-group mat-align-tabs="end">
  <div *ngFor="let item of assets; let i = index">
    <mat-tab label="{{i}}">
      <div class="container">
        <div class="map">
          <img id="img_equipment" [src]="apiUrl + '/path/to/svg/' + item">
          <a *ngFor="let link of map"
             title="{{ link.title }}"
             class="ink"
             [ngStyle]="{ left: link.left,top: link.top,width: link.width }">
          </a>
        </div>
      </div>
    </mat-tab>
  </div>
</mat-tab-group>

我提供了调用的返回值作为死代码中的注释。

例如,文件map-0.svg应该将此JSON用作映射map-mapping-0.json。然后,文件map-1.svg反过来就是这个JSON文件map-mapping-1.json

..并且调用返回的数组是否必须排序才能正常工作?因为不幸的是,它们当前未按后端排序返回。

解决方法

根据您的模板和说明,还不清楚您的数据应采用哪种形状以使其最容易实现。无论如何,我的直觉是转换数据,直到模板轻松使用它,然后再使用angular的异步管道。

# Output No. 1: -

Enter Your Name Jhon
Select a color 
 Blue 
 Red 
 Green 
 Yellow 
 Color: Blue
 Jhon You are Human

# Output No. 2

Enter Your Name Slave
Select a color 
 Blue 
 Red 
 Green 
 Yellow 
 Color: green
 Slave You are Lizard

这是一个大大简化的示例,但它具有基本结构。您加入并格式化数据,然后在视图中显示它。在此示例中,它只是字符串的元组,但是可以是您可以查看的嵌套// I'm making this an array of strings tuples,but it can // be whatever best serves your purpose displayData = Observable<Array<[string,string]>>; ngOnInit() { this.displayData = forkJoin({ mapData: this.myService.getMap(),mapAssets: this.systemMapService.getAssets() }).pipe( map(({mapData,mapAssets}) => { const formattedData = mapData.map(mapInstance => { // You're going to have to define this function yourself // to effective organsize/sort/whatever your data. const assetInstance = this.extractMapAsset(mapAssets,mapInstance); return [mapInstance,assetInstance]; }); return formattedData; }) ); } // In template <div *ngFor='let tupleData of displayData | async'> The map is called {{tupleData[0]}} and its assetJson is called {{tupleData[1]}} </div> 调用,可以根据需要随意显示数据。