简体   繁体   中英

Angular Chart.js is not working with $http call

I am using angular chart for populating a pie chart. For populating the chart I need to make a $http.get() call in service and call the service method from controller. But the chart is not working if I make $http call.

 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> 

If I un-comment the commented part, the pie chart works fine but I need to populate the value with $http call. How can I do that?

try sth like this:

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;
    });
}

you have to remember that this keyword refer to current context, so when you're in promise callback function this no longer points to your controller, but to callback function itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM