我有一个使用服务chartFactory.chartData
属性的控制器来提供一些数据供查看。问题是工厂在chartFactory.chartData
函数有时间从后端返回数据之前返回对象,因此该属性是未定义的。
我知道这是一个异步问题,但我不确定如何在工厂和控制器之间处理它。
chartFactory.js
app.factory('chartFactory', ['$http', '$interval', function($http, $interval) {
var service = {
get chartData() {
$http.get('/portfolio/get-chart-data')
.then(function(response) {
console.log(response.data, 'response data') //logging after undefined message
return response.data
})
}
}
return service
}])
chartController.js
app.controller('chartCtrl', function($scope, $timeout, $http, chartFactory) {
$scope.chartData = chartFactory
$scope.height_chart = window.innerHeight * 0.4
$scope.labels = chartFactory.chartData[0]; //undefined
$scope.series = chartFactory.chartData['GDAX Value']; //undefined
$scope.data = [
chartFactory.chartData[1] //undefined
];
$scope.onClick = function(points, evt) {
console.log(points, evt);
};
$scope.datasetOverride = [{
yAxisID: 'y-axis-1'
}];
$scope.options = {
responsive: true,
maintainAspectRatio: false,
scales: {
yAxes: [{
id: 'y-axis-1',
// type: 'linear',
display: true,
position: 'left',
ticks: {
beginAtZero: false,
callback: function(value, index, values) {
if (parseInt(value) >= 1000) {
return '$' + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
} else {
return '$' + value;
}
}
}
}],
xAxes: [{
display: false
}]
}
}
})
答案 0 :(得分:0)
将控制器更改为,
chartFactory.chartData().then(function(response) {
$scope.labels = getchartData .response.data[0];
$scope.series = chartFactory.response.data['GDAX Value'];
});