2015-05-09 28 views
1

我使用angular chart來填充餅圖。爲了填充圖表,我需要撥打服務中的$http.get()電話並從控制器調用服務方法。但是,如果我撥打$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調用來填充值。我怎樣才能做到這一點?

+0

但你有'GetMonthlyStatistics?month ='這不是一個網址... –

+0

它是一個URL,因爲我使用.net mvc與角度js ..和response.data.BranchNames返回我評論的確切數組對於標籤和response.data.BranchMonthlyTotalSale返回我爲數據評論的確切值。我看到它使用console.log。所以沒有問題。 – jubair

+0

你確定服務器的響應正常嗎?爲什麼你不使用拒絕處理函數作爲你承諾的'then'上的第二個參數函數? –

回答

1

嘗試某事像這樣:

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關鍵字是指當前上下文,所以當你在承諾的回調函數this不再指向你的控制器,但回調函數本身。

+0

非常感謝。你節省了我的一天。 – jubair