我的应用有问题。我有一个工厂,调用prepareStorage
将restApi
的所有静态变量保存到浏览器存储中(使用ngStorage
)。看起来像这样:
angular.module('panelApp')
.factory('prepareStorage', ['$localStorage', '$sessionStorage', 'apiService',
function($localStorage, $sessionStorage, apiService) {
var promise = {};
var load = function() {
apiService.call('head', 'staticTypes.json', [], function(response, status, head) {
if(angular.isUndefined($localStorage.staticTypes) || $localStorage.staticTypes.updatedAt < new Date(head()['last-modified'])){
delete $localStorage.staticTypes;
promise = apiService.call('get', 'statictypes.json', [], function (response) {
$localStorage.staticTypes = response;
}, function (errorObj) {
console.log(errorObj.error.message);
});
}
});
return promise;
return {
load: load()
};
}]);
然后我宣布了第二个工厂constantsService
,它给了我存储变量:
angular.module('panelApp')
.factory('constantsService', ['$localStorage', '$q', 'prepareStorage', '$timeout',
function($localStorage, $q, prepareStorage, $timeout) {
var output = {};
var deferred = $q.defer();
$timeout(function() {
deferred.resolve(prepareStorage.load, function() {
output = {
status: $localStorage.staticTypes.status
};
});
}, 1000);
return output;
}]);
现在我遇到了麻烦。
如果没有,我无法在控制器内部获得此存储变量 重新刷新。这意味着,在第一次网站刷新后, 控制器找不到
$localStorage.staticTypes.status
对象, 只有当我第二次刷新时才会这样做。
我正在寻找一种干净的解决方案,以避免使用$timeout
服务。
提前致谢。
答案 0 :(得分:0)
您是否尝试过使用这种不同的模式?
<强> prepareStorage 强>
angular.module('panelApp')
.factory('prepareStorage', prepareStorage);
prepareStorage.$inject = [ '$localStorage', '$sessionStorage', 'apiService' ];
function prepareStorage ($localStorage, $sessionStorage, apiService) {
var vm = this;
vm.load = function() {
return new Promise( function(resolve, reject){
apiService.call('head', 'staticTypes.json', [], function(response, status, head) {
if(angular.isUndefined($localStorage.staticTypes) || $localStorage.staticTypes.updatedAt < new Date(head()['last-modified'])){
delete $localStorage.staticTypes;
apiService.call('get', 'statictypes.json').then( function (response, error) {
if(response){
$localStorage.staticTypes = response;
return resolve(response);
}
return reject(error);
});
}
});
});
}
return {
load: load
};
});
constantsService
angular.module('panelApp')
.factory('constantsService', constantsService);
constantsService.$inject = [ '$localStorage', '$q', 'prepareStorage', '$timeout' ];
function constantsService($localStorage, $q, prepareStorage, $timeout) {
var vm = this;
vm.getStorage = function(){
prepareStorage.load().then( function( response){
return response;
});
}
return : {
getStorage : getStorage
}
}]);
我会将 apiService 重构为Promise
本身就像
. . .
//E.g. Method = get, document = statictypes.json
vm.call = function(method, document){
return new Promise( function (resolve, reject){
... do something
if(everyThingIsOk){
return resolve(response);
}
return reject(error);
});
}
我不能保证这是正确的100%,但如果您了解如何使用它应该有效。你只是等待承诺在做某事之前返回。我认为你应该像我一样构建你的apiService
,所以你也可以使用.then()
。
希望它有所帮助。