首页 > 解决方案 > 如何在 api 中将 JSON 对象转换为 Typescript 数组

问题描述

我有一个返回以下内容的 API 请求:

{
    "FarmerDetails": [
   {
    "userId": 1,
    "id": 1,
    "title": "delectus aut autem",
    "completed": false
  },
  {
    "userId": 1,
    "id": 2,
    "title": "quis ut nam facilis et officia qui",
    "completed": false
  }
]
}

我需要在单击按钮时显示标题,并且当按钮单击此“fetchPeople()”函数时会被调用。

fetchPeople() {
    this.peopleService.fetchPeople().subscribe((res:any)=>{
      this.people$ = res;
    });
  }

如何在打字稿中将我的对象转换为数组并显示特定或所有值。

标签: arraysjsonangularangular-cli

解决方案


当您从 api 获得响应时,它将以字符串格式返回。因此,您需要将其转换为 json 格式。将其解析为 json:

this.people=JSON.parse(res);

推荐阅读