为了账号安全,请及时绑定邮箱和手机立即绑定

Ag-Grid 动态设置列和行数据

Ag-Grid 动态设置列和行数据

陪伴而非守候 2021-12-02 15:32:10
我有一个 TypeScript 类,我在其中调用了一个调用后端 api 的方法,以从服务器获取数据以放入网格中。目前我有硬编码的列和行只是为了测试我将如何做到这一点。当我按照下面的示例放置列和行设置代码时,我会正确填充网格。export class FooComponent {  private columnDefs = [];  private rowData = [];  private gridOptions: GridOptions;  private data: any;  constructor(private http:HttpClient ) {     this.getFoo();this.gridOptions = <GridOptions>{};          this.gridOptions.columnDefs = [            {headerName: 'Make', field: 'make' },            {headerName: 'Model', field: 'model' },            {headerName: 'Price', field: 'price'}          ];          this.gridOptions.rowData = [            { make: 'Toyota', model: 'Celica', price: 35000 },            { make: 'Ford', model: 'Mondeo', price: 32000 },            { make: 'Porsche', model: 'Boxter', price: 72000 }          ];  }  getFoo(){    this.http.get(`https://xxx`).subscribe(response => {      this.data = response;    }, error => {      console.log(error);    });  }但是当我将列和行设置代码放在我想要的 getFoo 方法中时,我的网格数据没有设置,我得到了一个加载框。export class FooComponent {  private columnDefs = [];  private rowData = [];  private gridOptions: GridOptions;  private data: any;  constructor(private http:HttpClient ) {     this.getFoo();  }  getFoo(){    this.http.get(`https://xxx`).subscribe(response => {      this.data = response;    }, error => {      console.log(error);    });  }我试图通过从 getFoo 返回一个承诺,然后在承诺的“then”中设置列和行数据来解决这个问题,但得到了相同的加载框。这是我的标记。<ag-grid-angular     style="width: 700px; height: 500px;"     class="ag-theme-balham"    [gridOptions]="gridOptions"    ></ag-grid-angular>有任何想法吗?
查看完整描述

1 回答

?
繁星淼淼

TA贡献1775条经验 获得超11个赞

你可以这样做:


  export class FooComponent {

  private columnDefs = [];

  private rowData = [];

  private gridOptions$: Observable<GridOptions>;


  constructor(private http:HttpClient ) { 

 }

 ngOnInit() { this.getFoo(); } // call it here, not in constructor


 getFoo(){ 

   this.gridOptions$ = this.http.get(`https://xxx`);

 }

您可以通过对其执行 .map 并执行您的业务逻辑来转换 http 请求,并且该响应将是可观察的。


之后就在 html 中这样调用它:


<ag-grid-angular 

style="width: 700px; height: 500px;" 

class="ag-theme-balham"

[gridOptions]="gridOptions$ | async"

>

这将异步更新模型并为您触发更改检测。


查看完整回答
反对 回复 2021-12-02
  • 1 回答
  • 0 关注
  • 968 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信