我有一个在页面加载时加载的FirstController。当用户单击其上的按钮时,它会触发一个ng-switch,它加载一个SecondController,负责管理使用$ scope.data1,$ scope.data2,$ scope.data3中数据的3个图形的内容。当SecondController加载时,它初始化一个检索数据的服务。我的问题出在我当前的设置中。
myApp.controller('SecondController', ['DataService', function(DataService) {
DataService.getMyData(); // this starts a call to a service method that contains an $http call that gets the data. I don't want the DataService to be getting the data until SecondController is loaded.
$scope.myData1 = DataService.getAgeData(); // This fails now because the getMyData() call within the service has not completed when this is called.
$scope.myData2 = DataService.getNameData(); // This fails now because the getMyData() call within the service has not completed when this is called.
$scope.myData3 = DataService.getCountyData(); // This fails now because the getMyData() call within the service has not completed when this is called.
}]);
在HTML模板中,我有以下3次:
<chartdata data="myData1"></chartdata>
这样做的正确方法是什么?代码示例会有所帮助。
注意:getMyData()将数据推送到“this.asyncData”变量中。方法“getAgeData,getNameData和getCountyData”都对this.asyncData进行过滤/转换“,因此这些函数中没有$ http。
答案 0 :(得分:0)
如果DataService.getMyData()
中有一个$ http调用,则它是异步的,并且在您调用DataService.getAgeData()
时不一定完成。
如果您从$ http调用返回 承诺,则可以在getMyData()
完成后执行接下来的三种方法。
function getMyData() {
return this.$http
.get('....')
.then(function (response) {
//note that this return is an optional link in the promise chain,
//and it could just be a void operation here
return response.data;
});
}
我刚刚看了一下您的控制器,如果我是你,我实际上会改变它以将所有3设置为异步操作:
myApp.controller('SecondController', SecondController);
SecondController.$inject = ['DataService'];
function SecondController(DataService) {
DataService.getAgeData().then(function (ageData) { $scope.myData1 = ageData; });
DataService.getNameData().then(function (nameData) { $scope.myData2 = nameData; });
DataService.getCountyData().then(function (countyData) { $scope.myData3 = countyData; });
}
当你有机会时,一定要查看John Papa的风格指南,了解最佳实践 - 特别是“controllerAs”语法: https://github.com/johnpapa/angularjs-styleguide
根据您的评论进行更新:
function getMyData() {
return this.$http
.get('....')
.then(function (response) {
//note that this return is an optional link in the promise chain,
//and it could just be a void operation here
this.cachedData = response.data;
});
}
-
myApp.controller('SecondController', SecondController);
SecondController.$inject = ['DataService'];
function SecondController(DataService) {
DataService.getMyData().then(function () {
$scope.ageData = DataService.getAgeData();
$scope.nameData = DataService.getNameData();
$scope.countyData = DataService.getCountyData();
});
}