我想在控制器完成剩下的任务之前等待服务$ http结果。 我为myData测试了一些硬编码的JSON,它在控制器中是可见的,但只要我试图用$ http请求填充myData,控制器就不会等待它,只是通过代码的其余部分。 Chrome webdevelopper的网络标签显示了该请求的预期结果。
我已经具备以下条件:
var ListerApp = angular.module('ListerApp',[
'ListerAppFilters',
'sharedFactoryApp',
'sharedServiceApp',
'ListerAppController',
'infinite-scroll',
'angular-inview',
'ngRoute'
]);
ListerApp.config(['$routeProvider', '$httpProvider', function($routeProvider, $locationProvider) {
$routeProvider
.when('/list',
{
templateUrl: '/assets/services/partials/list.html',
controller: 'ListerCtrl',
resolve : {
'sharedServiceAppData': function($sharedServices){
// sharedFactoryAppData will also be injectable in your controller, if you don't want this you could create a new promise with the $q service
return $sharedServices.promise();
}
}
}
);
}]);
angular.module('sharedServiceApp', []).service('$sharedServices', ['$http', '$rootScope', '$q', function($http, $rootScope, $q) {
var myData = null;
return {
promise : function() {
if (!myData) {
$http({method : 'GET', url : '/shop/api/json', params : {
end : $rootScope.endmarkerSyncDataset,
page : 1,
per_page : $rootScope.itemsPerPage
}
}).success(function (data) {
myData = data.data_set;
//deferred.resolve(data.data_set);
});
// I allready tested this and this is OK: myData = {foo : 'bar'};
}
},
getShopData: function() {
return myData;
}
};
}]);
(function(){
var appController = angular.module('ListerAppController', []);
appController.controller('ListerCtrl', ['$scope', '$rootScope', '$http', '$filter', '$timeout', '$sharedFactories', '$sharedServices',
function($scope, $rootScope, $http, $filter, $timeout, $sharedFactories, $sharedServices) {
$scope.items = $sharedServices.getShopData();
console.log($scope.items); // return myData -> null
}
})();
感谢您的帮助。我找到了一些东西,并在下面发布。你的例子帮助我进一步创建一个API类对象。 – poashoas 2014-10-17 15:02:46