【发布时间】:2018-07-16 18:42:51
【问题描述】:
我有一个 API 响应以下 json 类型的对象:
{
"triggerCount": {
"ignition_state_off": 16,
"ignition_state_on": 14,
"exit_an_area": 12,
"enter_an_area": 19,
"door_unlocked": 1,
"door_locked": 1,
"fuel_level_below": 12
}
}
我通过这个注入的服务得到响应:
interface ITrigger{
triggerCount: ITriggerCount;
}
interface ITriggerCount{
[key:string]: number;
}
@Injectable()
export class DbApiService {
private triggersUrl = 'http://localhost:3000/triggers';
constructor(private http: HttpClient) {
}
getTriggerCount(){
return this.http.get<ITrigger>(this.triggersUrl)
}
}
我注入服务的组件:
export class TriggersComponent implements OnInit {
@Input() triggerCountChart = [];
triggers:any;
tempArray: any = [];
constructor(private triggerService: DbApiService) { }
ngOnInit() {
this.getTriggerCount()
this.buildChart()
}
getTriggerCount(){
this.triggerService.getTriggerCount().subscribe(data =>{this.triggers = data;
this.tempArray = this.triggers.triggerCount;
console.log(this.triggers,this.tempArray);
} );
}
如您所见,我在控制台记录了响应结果,因此我可以看到它的外观和工作方式,这是我浏览器中控制台的屏幕截图:
我真正想做的是提取属性字符串,例如ignition_state_off,并将它们保存在字符串类型的数组中,提取它们的值并将它们保存在类型数字的数组中,以便使用这些数组来呈现图表.
图表函数
此图表当前使用我手动插入的数据,您可以在 trigglerlabels 数组和 triggerCountArray 中看到:
buildChart(){
let triggerLabels = ['ignition_off','ignition_on','enter-area','exit-area','door_unlocked','door_locked','fuel_drop'];
let triggerCountArray = [12,13,22,32,14,8,17]
this.triggerCountChart = new Chart('canvas-triggers', {
type: 'pie',
data: {
labels: triggerLabels,
datasets: [
{
data: triggerCountArray,
// borderColor: "#3cba9f",
backgroundColor: ["#e8f1f2","#b9c0c1","#8d99ae","#3283a9","#006494","#283c4e"],
fill: false
},
]
},
options: {
title: {
display: true,
text: 'applets created in percentage',
fontSize:14
},
legend: {
display: true,
position: "right",
labels: {
boxWidth : 40,
fontSize : 14
}
},
scales: {
xAxes: [{
display: false
}],
yAxes: [{
display: false
}],
}
}
});
}
我希望我清楚地解释了这里的问题,我在网上查了很多地方都没有运气,请帮忙。
【问题讨论】:
-
您是否只是在寻找
Object.keys( this.tempArray )和Object.values( this.tempArray )(请注意,它们的顺序可能不一定相同)。或者你只是想要Object.keys( this.tempArray ).reduce( (current, item) => { current.labels.push( item ); current.values.push( this.tempArray[item] ); return current; }, { labels: [], values: [] } ) -
是的,我只想要键(如果键是指诸如“ignition_state_off”之类的标签)和值。但对我来说重要的是它们保持有序,否则我怎么知道标签对应的每个值?但会试试看。
-
那么我相信使用 reduce 的那个是最简单的
-
使用这个我的数组将是标签和值。我将如何在我的图表函数中使用它们(我的图表函数在同一个类中)我应该在类级别声明它们吗?我试图 console.log(labels) 但编辑抱怨它找不到名称标签
-
因为我已经在类级别上声明了标签和值,所以效果很好。但是标签和值中的第一个元素都不存在,所以我有 7 个元素,但在标签和值中,每个元素都有 6 个元素。问题出在哪里?
标签: json angular typescript observable