通过 http 请求将列动态添加到 ag-grid

Add columns dynamically to ag-grid from http request

我正在尝试根据 http 请求的响应将列动态添加到 ag-grid。

固定列是

 rowData: Task[];
 gridOptions: GridOptions;
 domLayout = "autoHeight";

 columnDefs = [
   { headerName: 'Titre', field: 'name', sortable: true, filter: true, width: 120 },
   { headerName: 'Collaborateur', field: 'collaborator', sortable: true, width: 250 },
   { headerName: 'Statut', field: 'status', sortable: true, width: 100 },
   { headerName: 'Lot', field: 'lot', sortable: true, width: 100 },
 ]

然后根据 http 响应,我想像这样添加新的列

{
  headerName: 'IC S1', valueGetter: function (params) { return params.data.charge[0] },
  editable: true, sortable: true, width: 60
},

我知道我做错了什么,但我不知道具体是什么。 这是我正在尝试的:

colDef = [];
newColumns() {
 this.rowData.forEach(task => {
  task.charge.forEach(initCharge => {

    let i = 0;
    this.colDef.push({ headerName: 'IC S' + (i + 1), field: 'initCharge', })
    });
  this.gridOptions.api.setColumnDefs(this.colDef);
  });
}

我在 ngOnInit

中调用所有这些
 ngOnInit() {
   this.subscription = this.route.params.subscribe(params => {
      this.id = +params['id'];
   });

   this.getProjectTasks();
   this.newColumns();
   this.getDates();
 }

这是我解决问题的方法,尽管不确定这是否是最好的做法。

 getProjectTasks() {
this.managerService.getTasksByProject(this.id).subscribe((resp) => {
  this.rowData = resp;
  let maxCharge = 0;
  this.rowData.forEach(task => {
    if (task.charge.length > maxCharge) {
      maxCharge = task.charge.length
    }
  });

  for (let i = 1; i < maxCharge; i++) {
    let j = i + 1;
    this.columnDefs.push({
      headerName: 'IC S' + j, valueGetter: function (params) { return params.data.charge[i] }, valueSetter: function (params) {
        if (params.data.charge[i] === params.newValue) {
          return false
        } else { params.data.charge[i] = params.newValue; return true }
      }, editable: true, sortable: true, maxWidth: 200
    })
  }

  this.gridOptions.api.setColumnDefs(this.columnDefs);
  this.gridOptions.api.sizeColumnsToFit();
},
  (err) => {
    console.log(err);
    }
  );
}