當前使用Angular JS和ChartJS嘗試在我的頁面上放置圖表。數據是通過NodeJS中的路由請求的,然後這些函數通過響應中的線索進行循環,並嘗試計算一個月中每天創建的數量。Chartjs/Javascript - 我的功能沒有正確返回數組,但控制檯日誌沒問題
當我控制檯登錄LeadsPerDay時,它會返回一個數組,其中包含我所期望的所有內容,但圖表似乎並未適當呈現這些點。它們全都落在底部,它告訴我找到我的陣列,因爲如果我把它拿出來,沒有點。如果我手動放入數組,它會正確渲染。
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: getDaysInMonth(currentMonth, currentYear),
datasets: [{
label: '# new leads created',
data: getLeadsForMonth(currentMonth, currentYear),
backgroundColor: [
'rgba(255, 99, 132, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
},
maintainAspectRatio: false
});
function getDaysInMonth(month, year) {
var date = new Date(year, month, 1);
var dates = [];
while (date.getMonth() === month) {
var currentDate = new Date(date).toISOString().replace(/T.*/, '').split('-').reverse().join('-');
var catDate = currentDate.replace(/-2017/g, '').replace(/-/g, '/').split('/').reverse().join('/');;
dates.push(catDate);
date.setDate(date.getDate() + 1);
}
return dates;
}
function getLeadsForMonth(month, year) {
// Create empty array to put leadCount in
var leadsPerDay = new Array();
/* Use $http.get to fetch contents*/
$http.get('/pipedrive/getLeadsForMonth', function() {}).then(function successCallback(response) {
// Loop through each lead and index them based on date
var leads = response.data.data[0].deals;
// Set date to first of the month
var date = new Date(year, month, 1);
// Define the month for the loop
var currentMonth = date.getMonth();
// Loop through the days in the month
while (date.getMonth() === currentMonth) {
// Save the date
var currentDate = new Date(date).toISOString().replace(/T.*/, '');
date.setDate(date.getDate() + 1);
leadCount = 0;
// Loop through each lead and search data for date
for (i = 0; i < leads.length; i++) {
if (leads[i].add_time.includes(currentDate)) {
leadCount++
}
}
leadsPerDay.push(leadCount);
}
}, function errorCallback(response) {
console.log('There was a problem with your GET request.')
});
console.log(leadsPerDay);
return leadsPerDay;
}
Bravo!謝謝你這麼徹底的解釋。 – Dadsquatch