我在 .run() 中有一个 ajax 调用,该调用将一个变量加载到 $rootScope 中,该变量在与视图关联的控制器中是需要的。
有时,在刷新 (F5) 时,当 .controller 加载时,$rootScope.SuperCategories 中没有任何内容。
sampleApp.factory('SuperCategoryService', ['$http', '$q', '$rootScope', function ($http, $q, $rootScope){
var SuperCategoryService = {};
SuperCategoryService.SuperCategories = $rootScope.SuperCategories;
alert ($rootScope.SuperCategories);
return SuperCategoryService;
}]);
sampleApp.run(function($rootScope, $q, $http) {
var req = {
method: 'POST',
url: 'SuperCategoryData.txt',
//url: 'http://localhost/cgi-bin/superCategory.pl',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }//,
//data: { action: 'GET' }
};
$rootScope.SuperCategories = [];
$rootScope.GetSuperCategories = function () {
var defer = $q.defer();
$http(screq).then(function(response) {
$rootScope.SuperCategories = response.data;
//alert ($rootScope.SuperCategories);
defer.resolve($rootScope.SuperCategories);
}, function(error) {
defer.reject("Some error");
});
return defer.promise;
}
$rootScope.GetSuperCategories();
});
如何修复这个错误。
注意:这不是直接回答你的问题。
我只是尝试以一种更常见的方式利用承诺和工厂的方式重写您的代码,也许它会给您一些可以改进的想法,以使异步代码更可预测地工作。
控制器 calls factory获取数据,以及何时Promise已解决,您的数据在$rootScope.SuperCategories
sampleApp.factory('SuperCategoryService', ['$http', '$q', function ($http, $q){
var req = {
method: 'POST',
url: 'SuperCategoryData.txt',
//url: 'http://localhost/cgi-bin/superCategory.pl',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }//,
//data: { action: 'GET' }
};
var SuperCategoryService = {};
SuperCategoryService.SuperCategories = function () {
var defer = $q.defer();
$http(screq).success(function(response) {
defer.resolve(response);
});
return defer.promise;
}
return SuperCategoryService;
}]);
sampleApp.controller('myController', ['$scope', 'SuperCategoryService', function($scope, SuperCategoryService) {
SuperCategoryService.SuperCategories().then(function(data){
$rootScope.SuperCategories = data;
});
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)