【问题标题】:Merge/Combine/Join two Observable arrays in one array and display it using ngFor together in Ionic 3 app在一个数组中合并/组合/加入两个 Observable 数组,并在 Ionic 3 应用程序中一起使用 ngFor 显示它
【发布时间】:2019-12-07 15:44:58
【问题描述】:

我在 Ionic 3 项目中使用 api 调用接收两个数组。我想在同一行显示它们的数据,像这样

[item1.1] [item2.1] 
[item1.2] [item2.2] 
[item1.3] [item2.3] 

不是这样的

[item1.1] [item1.2] 
[item1.3] [item2.1] 
[item2.2] [item2.3]

我尝试了不同的方法,例如使用 forkJoin 以及 combineLatest 完全显示第一个数组,然后是第二个

Observable.combineLatest(this.arr1, this.arr2).subscribe(
          (ValOne, ValTwo]) => {
            console.log(ValOne);
            console.log(ValTwo);
          }
        );

我以这种方式在 HTML 中显示组合数组,但它没有正确的顺序

      <div ion-item *ngFor="let x of (combinedArr | async)">
            <h2>{{ x.name }}</h2>           
            <h2> {{ x.id }} </h2>
      </div>

另外,我尝试在网格的两列中显示它,但它显示了相同类型的输出

<ion-grid>
    <ion-row>
        <ion-col *ngFor="let x of (arr1 | async);">
            <div>
                1 of 3 {{x.name}}
            </div>
        </ion-col>
        <ion-col>
            <div *ngFor="let y of (arr2 | async);">
                2 of 3 {{y.id}}
            </div>
        </ion-col>
    </ion-row>
</ion-grid>

【问题讨论】:

    标签: angular ionic-framework ionic3 observable ngfor


    【解决方案1】:

    你可以试试这样的:

    Observable.combineLatest(this.arr1, this.arr2).subscribe(
              ([ValOne, ValTwo]) => {
                const combinedArr = [];
                const length = Math.max(ValOne.lenght, ValTwo.length);
                for (let i = 0;i < length;i++) {
                  combinedArr.push([ValOne[i], ValTwo[i]);
                }
              }
            );
    

    combinedArr 中的每一项都是一行,由另一个表示列的数组组成:

    <ion-grid>
        <ion-row *ngFor="let cols of combinedArr;">
            <ion-col *ngFor="let col of cols;">
                <div>
                    1 of 3 {{col.name}}
                </div>
            </ion-col>
        </ion-row>
    </ion-grid>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-31
      • 1970-01-01
      • 2015-12-21
      • 1970-01-01
      • 2020-06-22
      • 2021-07-16
      • 2011-10-29
      • 1970-01-01
      相关资源
      最近更新 更多