[英]How to insert new interface types into an array in typescript
我想要实现的是具有此结构类型:
let chartDataSets: Array<ChartDataSets> = new Array<ChartDataSets>();
chartDataSets = [
{
backgroundColor: "#29b6f6",
borderColor: "#0086c3",
pointHoverBorderColor: "#0086c3",
pointHoverBackgroundColor: "#73e8ff",
pointRadius: 3.5,
fill: false
},
{
backgroundColor: "#f44336",
borderColor: "#ba000d",
pointHoverBorderColor: "#ba000d",
pointHoverBackgroundColor: "#ff7961",
pointRadius: 3.5,
fill: false
}
]
通过做这个:
data.forEach(element => {
chartDataSets.push(this.buildDatasets(element, timeSpan));
});
otherData.forEach(otherElement => {
chartDataSets.push(this.buildDatasets(otherElement, timeSpan));
});
我必须采用这种方式,因为我不知道该数组有多少个对象。 因此,我需要遍历服务返回的数据,以便知道数组中将有多少个对象。 但是我用push命令实现的是仅生成一个对象的数组,而不是将ChartDataSets的多个对象生成到数组中。
这是接口声明:
export interface ServiceResponse {
Date: Date;
Amount: number;
Precision: number;
}
export interface ChartDatasets {
data: ChartPoint[],
backgroundColor: string,
borderColor: string,
pointHoverBorderColor: string,
pointHoverBackgroundColor: string,
pointRadius: number,
fill: boolean
}
export interface ChartPoint {
x: number | string | Date
y: number
}
方法buildChartDatasets声明:
protected buildDatasets(element: EacSubmissionResponseModel, timeSpan: TimeSpan = TimeSpan.Day): ChartDataSets {
let chartDataset: ChartDataSets = {};
let chartResponse: ChartPoint[] = [{
x: element.Date,
y: element.Amount
}]
chartDataset.data = chartResponse;
return chartDataset;
}
这是我得到的响应,显示在chrome开发人员工具中:
第一个是期望的结果,第二个是我实际得到的结果。 希望这足够清楚。
因此,据我所知,您有一项服务可返回data
和otherData
变量,它们是element
的数组。
然后,您必须分别向this.buildDatasets
提供每个element
,以获取ChartDataSets
,然后将每个返回的值推送到chartDataSets
Array。
这意味着this.buildDatasets
具有以下签名:
buildDatasets(element: T, timeSpan): ChartDataSets
类型T
是返回的每个element
的类型。 因此, data
和otherData
必须为T[]
类型。
请检查data
变量的类型以及this.buildDatasets
的返回类型。
我可以解决我的问题,这就是我的方法:
let chartDataSets: Array<ChartDataSets> = new Array<ChartDataSets>();
let chartPoints: Array<ChartPoint> = new Array<ChartPoint>();
this._service.getData().subscribe(data => {
data.forEach(element => {
chartPoints.push(this.buildDatasets(element, timeSpan));
});
chartDataSets.push({
data: chartPoints
})
});
这是buildDatasets的签名:
protected buildDatasets(element: EacSubmissionResponseModel, timeSpan: TimeSpan = TimeSpan.Day): ChartPoint
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.