У меня есть несколько объектов, которые я получаю один за другим, используя функцию settimeout, а затем каждый раз помещаю в массив, чтобы заполнить таблицу. Это происходит в моем проекте динамически, но просто для справки я использую settimeout и жесткое кодирование здесь. Он работает нормально, но «status» (json key) заменяется после сопоставления с vehicle_number, но вместо замены мне просто нужно заполнить значение «status» один за другим. Вот код ниже https://stackblitz.com/edit/angular-oz6mwm?file=src%2Fapp%2Fapp.component.ts
app.component. html
<hello name="{{ name }}"></hello>
<p>
Start editing to see some magic happen :)
</p>
<div>
<table>
<tr *ngFor="let x of groupList">
<td>{{x.vehicle_number}}</td>
<td>{{x.status}}</td>
</tr>
</table>
</div>
app.component. html
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
name = 'Angular';
imageSource: any;
statusdata1: any;
vehicle_number: any;
groupList: any = [];
ngOnInit() {
/* First data */
this.statusdata1 = {"vehicle_number":1,"status":"red"};
this.updateGroupList(this.statusdata1);
console.log(this.groupList);
/* Second data */
setTimeout (() => {
this.statusdata1 = {"vehicle_number":1,"status":"green"};
this.updateGroupList(this.statusdata1);
console.log(this.groupList);
}, 5000);
/* Third data */
setTimeout (() => {
this.statusdata1 = {"vehicle_number":2,"status":"yellow"};
this.updateGroupList(this.statusdata1);
console.log(this.groupList);
}, 10000);
}
private updateGroupList(statusData: any) {
for (const key in this.groupList) {
if (this.groupList[key].vehicle_number === statusData.vehicle_number) {
this.groupList[key].status = statusData.status;
return;
}
}
this.groupList.push(statusData);
}
}