获取 API 响应并将数据存储到数组中

Get the API response and store the data in to an array

我正在尝试从我的 Angular 应用程序调用 API 并取回数据,将数据用于我的前端。我收到了回复,但我不确定如何从 JSON 中获取特定字段并将它们存储到数组

 dataList;
 apiUrl = 'GetDatafromSys?prj=123;

 constructor(service: DataService) {
 service.get<any>(this.apiUrl).subscribe(x => {this.dataList = (JSON.stringify(x)); });
}

我得到了 dataList 作为 JSON 就像

 [
  {
    "Name": "Jack",
    "EmpNo":"123"
  },
  {
   "Name": "Joe",
    "EmpNo":"456"
  }
 ]

我不确定如何从 JSOn 中获取 Name 并将其存储在数组中以便我可以将其用作下拉列表的数据源

  <dx-select-box [dataSource]=""

您可以为您的员工创建一个界面:

export interface Employee{
Name:string;
EmpNo:number;
}

现在,您可以修改您的构造函数,消除您的员工界面的 "any",并将此类型添加到您的数据列表中。

 dataList: Employee[];
 apiUrl = 'GetDatafromSys?prj=123;

 constructor(service: DataService) {
 service.get<Employee[]>(this.apiUrl).subscribe(x => {this.dataList = x }); // here you assign your results to your datalist array
}

现在,您可以通过访问元素的位置来获取任何元素的 属性。或者使用 foreach 函数来获取您需要的任何名称。 例如:

public print(){
this.dataList.forEach(element => {
  console.log(element.Name);
});

}

希望这能让您了解如何存储您的信息。