【问题标题】:How do I use data from a rest response into ag-grid using javascript?如何使用 javascript 将来自休息响应的数据用于 ag-grid?
【发布时间】:2021-08-22 21:29:53
【问题描述】:

我对 javascript 和 ag-grid 还很陌生,并且一直在按照教程中的内容继续前进。

在 ag-grid 的教程中,可以使用以下代码获取远程数据:

  // fetch the row data to use and one ready provide it to the Grid via the Grid API
  agGrid.simpleHttpRequest({url: 'https://www.ag-grid.com/example-assets/row-data.json'})
      .then(data => {
          gridOptions.api.setRowData(data);
      });

但是如果我想使用来自 api 调用的数据怎么办?说出来自这个 URI 的 JSON 响应:https://api.opencritic.com/api/game/1520

希望有人能解释一下。谢谢!

【问题讨论】:

    标签: javascript ag-grid


    【解决方案1】:

    您可以在将数据传递给 setRowData 之前对数据执行所需的任何转换:

    agGrid.simpleHttpRequest( ... )
      .then(data => {
    
        // transform the data into whatever format you need
        const rowData = data.reduce(...) // or whatever. not _necessarily_ reduce
    
        gridOptions.api.setRowData(rowData);
    
      })
    

    根据您的评论,您将获得一个对象{},而不是discounts 的数组[]。我建议您在 API 端解决此问题,以便从一开始就获得一个数组,但假设这是不可能的,转换它是微不足道的。

    给定一个对象x,调用Object.values(x) 将得到x 中的 数组。例如:

    const x = {
      foo: 'a',
      bar: 'b',
      baz: 'c',
    }
    
    const v = Object.values(x);
    
    // v is now ['a', 'b', 'c']
    

    值也可以是对象。你得到一个对象数组:

    const x = {
      foo: { label: 'a', bang: 1 },
      bar: { label: 'b', bang: 2 },
      baz: { label: 'c', bang: 3 },
    }
    
    const v = Object.values(x);
    
    // [{ label: 'a', bang: 1 }, { label: 'b', bang: 2 }, { label: 'c', bang: 3 }]
    

    现在你有了一个数组,你可以使用像map这样的数组方法来转换它:

    const bangs = v.map(value => value.bang);
    // [1, 2, 3]
    

    注意:所有这些示例都使用implicit return 语法来表示arrow functions

    如果您愿意,可以使用destructuring 来收紧上述表达式。下面的表达式在功能上等同于上面的表达式,没有重复“值”。在这种情况下并没有太大区别,但如果您需要输入对象中的多个字段,它就会开始累加。

    const bangs = v.map(({bang}) => bang);
    // [1, 2, 3]
    

    解构还提供了一种在输入过程中重命名字段的机制。下面的示例将bang 重命名为x 并返回一个具有x 属性的对象:

    // v = [{ label: 'a', bang: 1 }, { label: 'b', bang: 2 }, { label: 'c', bang: 3 }]
    
    const bangs = v.map(({bang: x}) => ({x}));
    // [{x: 1}, {x: 2}, {x: 3}]
    

    您可以使用多个字段进行这种速记解构/重命名。在这里,我们将bang 重命名为x,将label 重命名为y,并返回一个具有这些属性的新对象:

    // v = [{ label: 'a', bang: 1 }, { label: 'b', bang: 2 }, { label: 'c', bang: 3 }]
    
    const bangs = v.map(({bang: x, label: y}) => ({x, y}));
    // [{x: 1, y: 'a'}, {x: 2, y: 'b'}, {x: 3, y: 'c'}]
    

    使用这种方法,您可以将discounts 对象中的BasePriceSalePrice 字段重新映射为您需要的任何格式。在下面的示例中,我将它们重新映射到具有xy 属性的对象数组。我不知道这就是 agGrid 所期望的,但调整它以满足您的需求应该很简单。

    // function that converts the sample data format to an array of
    // coordinates, e.g. [{ x: 555, y: 999 }, { x: 123, y: 456 }]
    function transform (input) {
      return Object.values(input.discounts)
        .map(({BasePrice: x, SalePrice: y}) => ({x, y}))
    }
    
    fakeApiRequest() // simulate the request
      .then(apiData => {
        const rowData = transform(apiData); // transform the response data
        show(rowData); // show the result
    })
    
    //-------
    // everything below is just utility and convenience stuff
    // for the demo. mostly irrelevant/ignorable for your purposes
    //-------
    
    // sample data
    const sampleData = {
      "discounts": {
        "0": { "BasePrice": "1499", "SalePrice": "449" },
        "1": { "BasePrice": "1299", "SalePrice": "519" }
      }
    }
    
    // simulates an api request; waits a moment then resolve with sample data.
    // not really relevant to your issue; just hand-waving for the demo
    async function fakeApiRequest () {
      return new Promise(resolve => {
        setTimeout(() => resolve(sampleData), 100)
      });
    }
    
    // irrelevant. just a convenience utility for showing the output.
    function show(d) {
      document.querySelector('pre').innerHTML = JSON.stringify(d, null, 3);
    }
    <pre></pre>

    【讨论】:

    • 嗨,雷,感谢您的回复。我认为我的问题不够清楚。我想问的是,如何声明一个 ag-grid 请求以从 API 获得响应?我还用 simpleHttpRequest 吗?
    • 我想我不明白你在这里所做的“API”区别。这是一个返回 json 的 http 请求。与教程示例有何不同?
    • 我刚刚意识到是的,没有区别,它对我不起作用的原因是因为教程示例有一个带有以“[”开头的数组的 json 文件。我试图开始工作的 api 响应格式如下:{ "discounts": { "0": { "BasePrice": "1499", "SalePrice": "449", }, "1": { "BasePrice": "1299", "SalePrice": "519", } } } 知道如何将 BasePrice、SalePrice 设置为我的行数据吗?谢谢!
    • 非常感谢您!我的问题解决了!
    猜你喜欢
    • 2019-03-10
    • 2021-03-14
    • 2021-12-06
    • 2019-07-11
    • 2016-10-23
    • 2019-05-31
    • 2021-09-16
    • 2021-10-14
    • 2021-10-09
    相关资源
    最近更新 更多