我正在尝试迭代一个数组,该数组包含一些我想呈现给用户的值。我在用 Angular 提取这些值时遇到一些困难。我不确定我做错了什么。我收到了响应,所以我知道请求正在返回,但是我似乎无法访问或循环访问数组的各个部分。
C# 代码:
[EnableCors(origins: "http://localhost:4200", headers: "*", methods: "*")]
public class MapController : ApiController
{
Map[] map = new Map[]
{
new Map { Map_Data_ID = 122, County = "West Yorkshire", Color = "#d45faa"},
new Map { Map_Data_ID = 122, County = "West Yorkshire", Color = "#d45faa"},
};
public IEnumerable<Map> GetAllProducts()
{
return map;
}
}
Angular :
test: Array<{id: Number, value: string, color: string}> = [];
getMapData() {
this._interactiveMapService.getMapData()
.subscribe(
data => {
var arr = Object.keys(data).map(key => ({type: key, value: data[key]}));
for(var i; i < arr.length; i++) {
this.test.push({id: i.Map_Data_ID, value: i.County, color: i.Color});
}
})
}
这也是我想要附加响应数据的
示例:
this.dataSource = {
chart: {
caption: "Depot Locations",
subcaption: "United Kingdom (Counties)",
numbersuffix: "%",
includevalueinlabels: "1",
labelsepchar: ": ",
entityFillHoverColor: "#FFF000",
theme: "fint",
},
// Source data as JSON --> id represents counties of england.
data: [
{
id: "126",
value: "Anglesey",
color: "#d45faa"
},
{
id: "108",
value: "Argyl & Bute",
color: "#d45faa"
}
]
}
服务器响应示例:
[
{
"Map_Data_ID": 122,
"County": "West Yorkshire",
"Color": "#d45faa"
},
{
"Map_Data_ID": 167,
"County": "Wiltshire",
"Color": "#d45faa"
}
]
最佳答案
假设响应的格式如下:
data = [ { "Map_Data_ID": 122, "County": "West Yorkshire", "Color": "#d45faa" }, { "Map_Data_ID": 167, "County": "Wiltshire", "Color": "#d45faa" } ];
您可以使用
.subscribe(data => {
this.data.forEach(e => {
this.test.push({
id: e.Map_Data_ID,
value: e.County,
color: e.Color
})
})
});
由于我们处于 typescript 的世界,我们可以定义一个类来保存这些数据,让我们的生活更轻松。
export class CountryDetails {
constructor(
private id: number,
private value: string,
private color: string
) {}
}
现在使用新创建的类:
.subscribe(data => {
this.data.forEach(e => {
this.test.push(new CountryDetails(e.Map_Data_ID, e.County, e.Color));
})
});
关于c# - 循环遍历响应对象 Angular ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59217250/