【问题标题】:Display API JSON response in template - Angular在模板中显示 API JSON 响应 - Angular
【发布时间】:2020-12-03 05:45:03
【问题描述】:

我想在我的网站上显示来自 URL 的 JSON 文件的数据。 我在 Angular 上工作,并且在我的组件中创建了一个 HttpClient 。下面的代码显示了控制台中的所有文档,所以这是我的问题。

  let resp = this.http.get("https://spreadsheets.google.com/feeds/cells/1w2vpgbwImaQGCbpMqZ3P0NC93tuVved0oOFc9Zr22dU/1/public/full?alt=json");
   resp.subscribe((data)=>console.log(data));
   

我可以显示此 JSON 文件中的指定元素吗?

我想在我的网站上显示来自:feed -> entry -> gs$cell -> $t 的数据。 我应该如何开始,我需要什么?

我添加了一张 JSON 数组的外观图片以及我想要在我的网站上获取和显示的元素。

【问题讨论】:

  • 在你的控制台上试试这个fetch("https://spreadsheets.google.com/feeds/cells/1w2vpgbwImaQGCbpMqZ3P0NC93tuVved0oOFc9Zr22dU/1/public/full?alt=json").then(r => r.json()).then(d => console.log(d.feed.entry.map(e => e['gs$cell']['$t'])))
  • @bertdida 感谢您的回复!我已经在我的控制台上尝试过了,是的,这显示了我想要的数据,但我想在我的网站上显示这些数据,所以我想将它传输到 HTML 并保存在表格中。有什么建议我该怎么做?

标签: javascript html json angular


【解决方案1】:

将 API 响应存储在类变量中,即 data,假设样本数据

  data = {
    feed: {
      entry: [
        { gs$cell: { $t: 'Nazwa' } },
        { gs$cell: { $t: 'pazwa' } },
        { gs$cell: { $t: 'shuzwa' } }
      ]
   }
 }

直接在模板中访问

<div *ngFor="let d of this.data.feed.entry">{{d.gs$cell.$t}}</div> 

【讨论】:

    【解决方案2】:

    在我看来,您的问题是如何提取数据。

    我不能使用你的 HttpClient,所以我将使用fetch API 进行演示。

    async function getData() {
      const endpoint =
        "https://spreadsheets.google.com/feeds/cells/1w2vpgbwImaQGCbpMqZ3P0NC93tuVved0oOFc9Zr22dU/1/public/full?alt=json";
    
      // const json = await http.get(endpoint);
    
      const response = await fetch(endpoint);
      const json = await response.json();
    
      const { feed } = json;
      const { entry: feedEntries } = feed;
    
      return feedEntries.map((entry) => {
        const { gs$cell } = entry;
        const { $t } = gs$cell;
        return $t;
      });
    }
    
    (async () => {
      const data = await getData();
      console.log(data);
    
      // do whatever you wan't with the data, use it on your template maybe?
    })();

    【讨论】:

    • 非常感谢!它工作得很好,但我想在表中显示这些数据,其中“Nazwy”和“Numery”是列的名称。在控制台中,“data”是一个包含 11 个元素的数组,前两个元素 data[0] 和 data[1] 是列的名称。现在在表格中显示网站上的数据将非常困难(实际上我想准确地显示数据在谷歌表格上的样子)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-18
    • 2018-07-18
    • 2021-10-21
    • 2022-09-25
    • 2018-08-19
    相关资源
    最近更新 更多