如何使用打字稿获取对象数组的长度

时间:2019-11-25 16:37:09

标签: javascript angular typescript

我正在尝试使用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;

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

1 个答案:

答案 0 :(得分:1)

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

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