[英]angular chartjs not showing data properly
我正在使用Angular 6,並嘗試實現Chart.js折線圖。 基本上,我要為兩個數組調用API: weight_data
數組和weight_date
數組,並將它們用於圖表。
我將從API請求中獲得的數組存儲在兩個實例中: this.weight_date
和this.weight_data
。
這是圖表的代碼:
// code for chart here
this.chart = new Chart(this.chartRef.nativeElement, {
type: 'line',
data: {
labels: this.weight_date, // your labels array
datasets: [
{
data: this.weight_data, // your data array
borderColor: '#e0573a',
fill: true
}
]
},
options: {
legend: {
display: false
},
scales: {
xAxes: [{
display: true
}],
yAxes: [{
display: true
}],
},
title: {
display: true,
text: 'Weight Tracker',
fontFamily: "'Montserrat', sans-serif",
fontColor: '#272727',
fontSize: 18,
padding: 12
},
layout: {
padding: {
left: 10,
right: 20,
top: 0,
bottom: 0
}
},
gridLines: {
drawOnChartArea: true
},
}
});
當我使用預編碼的數組(日期為["11/02/18", "11/03/18", "11/04/18"]
和權重為[65, 66, 67]
["11/02/18", "11/03/18", "11/04/18"]
,它可以正常工作。 但是,當我嘗試使用兩個實例時,圖表變成空白。 沒有任何錯誤,只是空白。
我先進行API調用,然后分別在ngOnInit
初始化圖表。 我在這里想念什么?
似乎您想訂閱一個可以提供數據的Observable,一旦輸入,就可以初始化圖表。 通常,我們希望在服務內進行HTTP調用,但是為了簡化起見,這是我們可以在組件內進行的操作:
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
import {Component, OnInit} from '@angular/core';
export class MyChart implements OnInit {
constructor(private http: HttpClient) { }
private getData() {
let url = '[SOME-URL]' // your path to the data API endpoint
return this.http.get(url) as Observable<Array<any>>; // you would want to use correct typings here, instead of <any>
}
ngOnInit() {
this.getData().subscribe((data: any) => {
console.log(data);
// assign your data here, and then initialize your chart.
});
}
}
我只是發現自己在做錯什么:我使用的是基於Promise的axios,因此考慮@JeffFhol的建議,由於我在初始化API的同時初始化圖表,所以我的兩個實例是空白的請求。
解決方案是在axios請求的then
子句中初始化圖表,以確保我的實例不為空。
這是有效的代碼段:
axios({
method: 'post',
url: 'url_to_api',
headers: {
'Content-Type' : 'application/json'
// custom data headers, etc.
},
data: {
// data to be sent
}
})
.then(response => {
this.weight_dates = response.data.weight_date;
this.weight_data = response.data.weight_data;
// code for chart here
})
.catch(error => {
console.log(error)
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.