首页 > 解决方案 > 如何使用打字稿来获取对象数组的长度

问题描述

我试图通过使用 API 调用从后端获取对象数组的长度。这是“区域”目标的样子:

[
    {
        "id": 1,
        "name": "a"
    },
    {
        "id": 2,
        "name": "b"
    },
    {
        "id": 3,
        "name": "c"
    },
    {
        "id": 4,
        "name": "d"
    }
]

并且以下打字稿代码未正确返回长度:

var lengthZones= Object.keys(this.swimbandsService.getZones()).length;

在打字稿中获取对象数组长度的正确方法是什么?

标签: javascriptangulartypescript

解决方案


我猜您需要先等待 Promise 解决,然后您才能访问响应并计算数组中的对象。

this.swimbandsService.getZones().then((response) => {
  // might need to parse the response as json, depending on your service logic
  var lengthZones = response.length;
});

推荐阅读