我试图动态更改我的数据,而不是继续请求服务器。
这是我目前的代码:
$scope.total_earned = () => { //ng-click function from frontend
splice();
loadChartData(1);
};
$scope.total_cashback = () => { //ng-click function from frontend
splice();
loadChartData(2);
};
loadChartData(1);
function splice(){
$scope.chartConfig.series = [];
}
function loadChartData(type) {
Vendor.get({id: vendorId}).$promise.then((data) => {
$scope.datePicker = {startDate: moment(data.metadata.start_date), endDate: moment(data.metadata.end_date)};
$scope.data = data;
for (var key in data) {
var arr = [];
var arr2 = {};
if (data.hasOwnProperty(key)) {
if (key != 'metadata') {
var obj = data[key];
$.map(obj, function (el, index) {
var date = moment.utc(el.date).valueOf();
var value = 0;
if (type == 1) {
value = el.total_amount;
}
else if (type == 2) {
value = el.total_earned;
}
else if (type == 3) {
value = el.total_spent;
}
arr.push([date, parseInt(value)]);
arr2[key] = arr;
});
$scope.chartConfig.series.push(
{
name: key,
type: 'line',
data: arr2[key],
animation: true
}
);
} else {
break;
}
}
}
});
}
我的json输出:
{
"vendor1": [{
"total_earned": "313028",
"total_spent": "92231",
"total_amount": "3222509",
"date": 1450828800
}, {
"total_earned": "281966",
"total_spent": "87324",
"total_amount": "2906973",
"date": 1450915200
}, {
"total_earned": "265567",
"total_spent": "82190",
"total_amount": "2737860",
"date": 1451001600
}],
"vendor2": [{
"total_earned": "114122",
"total_spent": "41223",
"total_amount": "512123",
"date": 1450828800
}, {
"total_earned": "125613",
"total_spent": "16678",
"total_amount": "9764231",
"date": 1450915200
}, {
"total_earned": "12546",
"total_spent": "16164",
"total_amount": "17758",
"date": 1451001600
}]
}
问题是每当我调用total_earned
或total_cashback
函数时,它总是加载到服务器。我知道它总是调用loadChartData
函数并运行服务器。我试图将数据放到$scope.data
,但每当我在函数外部调用它时,数据都是undefined
。
任何解决方案,以便我可以根据类型不断更改数据而不将其加载到服务器?
答案 0 :(得分:1)
我不确定你究竟是在追求什么,但你应该将调用结果存储在变量中的loadChartData中,然后你可以随时访问它。例如:
var data = loadChartData(type);
data.then(function(values) {
// do something with values
});
问题是你要返回一个promise而不是一个值,每次调用你的loadChartData函数时,你都会从服务器获取结果并返回一个新的promise。您可以简单地重用原始承诺。如果您对角度承诺知之甚少,请参阅here。
您需要将数据提取调用与业务逻辑分开,这样,您可以通过一次调用获取,获取所有适当的数据,然后以您希望的任何方式使用它,如下所示: / p>
function loadChartData() {
return Vendor.get({id: vendorId}).$promise;
});
var data = loadChartData();
data.then(function(data) {
//do something with data
});
data.then(function(data) {
//do something else with data
});