【问题标题】:AgGrid rowData not updating inside "subscribe" call on Observable objectAgGrid rowData 未在 Observable 对象的“订阅”调用中更新
【发布时间】:2018-12-11 03:14:59
【问题描述】:

我相当肯定这与范围问题有关,但我在网上找不到任何关于它的信息。我有一个服务,它从一个 API 返回一个基本的 Observable,其中包含我想要更新我的 rowData 变量的数据。

MyService.ts

 fetchDummyData(): Observable<DummyResponse[]> {
    return this.http.get<DummyResponse[]>('***SOME_API***');
 }

我的组件

如果我在这里尝试向 rowData 添加数据,则网格不会更新

rowData = [];
/////////////
////////////Other stuff

this.myService.fetchDummyData().subscribe(
  data => {
    for (let i = 0; i < data.length; i++) {
      this.rowData.push(
        {
          idType: 'ID Type ' + (i + 1),
          description: 'adfasdf'
        }
      )
      //This log prints the correct thing, but rowData remains empty outside the loop
      console.log('Row id: ' + this.rowData[i].idType);
    }
  }
)

但如果我在上面的 subscribe 调用之后添加它,它会起作用。

rowData = [];
/////////////
////////////Other stuff

this.myService.fetchDummyData().subscribe(
  data => {
    for (let i = 0; i < data.length; i++) {
        //Do Nothing
    }
  }
)

//This actually updates the rowData
this.rowData.push(
    {
      idType: 'ID Type ' + (i + 1),
      description: 'adfasdf'
    }
  )

为什么 rowData 不在 subscribe 调用中全局更新?

【问题讨论】:

标签: javascript angular observable ag-grid


【解决方案1】:

您可以在订阅者内部使用api.setRowData(newData)

this.myService.fetchDummyData().subscribe(
    data => {
    let rows = [];
    for (let i = 0; i < data.length; i++) {
        rows.push({
            idType: 'ID Type ' + (i + 1),
            description: 'adfasdf'
        });
    }
    this.gridApi.setRowData(rows);
  }
)

【讨论】:

    【解决方案2】:

    在订阅中,您应该调用markForCheck change detection。

    constructor(
     private cd: ChangeDetectorRef
    ) { }
    
    ngOnInit() {
      this.myService.fetchDummyData().subscribe(
        data => {
          for (let i = 0; i < data.length; i++) {
            this.rowData.push(
              {
                idType: 'ID Type ' + (i + 1),
                description: 'adfasdf'
              }
            )
            this.cd.markForCheck()  // Add this code.
          }
        }
      )
    }
    
    

    否则需要存储网格的API并显式调用gridApi.setRowData(this.rowData)

    【讨论】:

      猜你喜欢
      • 2019-01-20
      • 1970-01-01
      • 2013-04-17
      • 2019-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-28
      • 1970-01-01
      相关资源
      最近更新 更多