我正在使用angular chart用于填充饼图。为了填充图表,我需要在服务中进行 $http.get()
调用并从 Controller 调用服务方法。但如果我进行 $http
调用,图表将无法工作。
angular.module('shopAdminApp')
.service('ChartService', ['$http',ChartService])
function ChartService($http) {
this.GetAllChartData = function (month, year) {
return $http.get('GetMonthlyStatistics?month=' + month + '&&year=' + year + '');
}
}
angular.module('shopAdminApp')
.controller('chartCtrl', ["ChartService", ChartCtrl]);
function ChartCtrl(ChartService) {
// this.labels = ["Download Sales", "In-Store Sales", "Mail-Order Sales"];
// this.data = [10, 20, 100];
var promise = ChartService.GetAllChartData(12, 2012);
promise.then(function (response) {
console.log(response.data);
this.chartsdata = response.data;
this.labels = response.data.BranchNames;
this.data = response.data.BranchMonthlyTotalSales;
});
// console.log(this.chartsdata);
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<canvas id="pie1" class="chart chart-pie" data="chart.data" labels="chart.labels" height="300" width="400"></canvas>
如果我取消注释注释部分,饼图可以正常工作,但我需要使用 $http
调用填充该值。我怎样才能做到这一点?
最佳答案
尝试这样:
function ChartCtrl(ChartService) {
var self = this;
var promise = ChartService.GetAllChartData(12, 2012);
promise.then(function (response) {
self.chartsdata = response.data;
self.labels = response.data.BranchNames;
self.data = response.data.BranchMonthlyTotalSales;
});
}
你必须记住 this
关键字引用当前上下文,因此当你处于 Promise 回调函数中时 this
不再指向你的 Controller ,而是指向回调函数本身。
关于javascript - Angular Chart.js 不适用于 $http 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30142189/