如何在Angular中使用ngFor同时迭代两个数组?

时间:2018-09-06 09:40:44

标签: angular typescript

我必须将对象数组作为来自node.js的有效载荷,并将其存储在不同的变量中并进行迭代,但是* ngFor只迭代第一个循环而不是第二个循环,因此如何在相同的div上进行迭代 status.component.html

<div *ngFor="let payload1 of payload1;let payload2 of payload2;">
  <h4>{{payload2.username}}</h4>
  <h4>{{payload1.date}}</h4>
</div>

status.component.ts

payload1 = [];
payload2 = [];

ngOnInit() {
  this.statusService.getStatusDetails(this.statusObj).subscribe(
    (data) => {
      if(data.status == 26){
        this.payload1 = data.payload[0];
        this.payload2 = data.payload[1];
      }
    }
 );
}

2 个答案:

答案 0 :(得分:4)

我认为,如果您的有效载荷长度相同且有序匹配(您的问题似乎暗示确实如此),这应该可行

<div *ngFor="let p of payload1;let i = index">
  <h4>{{payload2[i].username}}</h4>
  <h4>{{payload1[i].date}}</h4>
</div>

答案 1 :(得分:1)

为什么不从中制作单个阵列?

payload = [];
ngOnInit() {
  this.statusService.getStatusDetails(this.statusObj).subscribe(
    (data) => {
      if(data.status == 26){
        this.payload = data.payload[0]
          .map((item, index) => ({ ...item, ...data.payload[1][index] }));
      }
    }
 );
}

片段证明有效:

const d1 = [
  { id: 0 },
  { id: 1 },
];

const d2 = [
  { name: '0' },
  { name: '1' },
];

const d3 = d1.map((item, index) => ({ ...item, ...d2[index] }));

console.log(d3);

如果数组的长度不同,您甚至可以构建此合并的有效负载。

const d1 = [
  { id: 0 },
  { id: 1 },
];

const d2 = [
  { name: '0' },
  { name: '1' },
  { name: '2' },
];

const longest = d1.length > d2.length ? d1 : d2;
const shortest = d1.length <= d2.length ? d1 : d2;

const d3 = longest.map((item, index) => ({ ...item, ...shortest[index] }));

console.log(d3);

角度版本:

payload = [];
ngOnInit() {
  this.statusService.getStatusDetails(this.statusObj).subscribe(
    (data) => {
      if(data.status == 26){

        const longest = data.payload[0].length > data.payload[1].length ? 
          data.payload[0] : data.payload[1];
        const shortest = data.payload[0].length <= data.payload[1].length ? 
          data.payload[0] : data.payload[1];

        this.payload = longest
          .map((item, index) => ({ ...item, ...shortest[index] }));
      }
    }
 );
}