【发布时间】:2017-02-14 13:18:00
【问题描述】:
我的应用程序有一些配置数据存储在我的 API 服务器上(在本例中为 form.io),由于它很少更改,我想将其存储在 localStorage 中,然后根据需要进行更新。因此,在我的 getStationConfig 服务中,我会检查 localStorage 中的数据,如果不存在,则从 API 中获取并将其存储在本地以备下次使用。
问题是在 promise 中从 localStorage 返回数据,以便我的控制器代码可以处理它。从我的控制器获取数据的代码是这样的:
var stationPromise = shiftService.getStationConfig().then(function(data) {
vm.configSlots = data;
});
我的服务看起来像这样:
var getStationConfig = function() {
// First check to see if info is stored locally.
var config = JSON.parse(localStorage.getItem('cfdConfig'));
if (config) {
return config;
}
// Get position info from appropriate Config resource submission.
// Code borrowed from ngFormioHelper.FormioAuth.
var token = localStorage.getItem('formioToken');
var config = {
disableJWT: true,
headers: {
"x-jwt-token": token
}
};
return $http.get(Formio.getAppUrl() + '/config/submission', config)
.then(function(result) {
// Code goes here to format the data for return to the controller
// Now that it's all formatted, store the info in localstorage so that it can be retrieved from there
// later and we don't have to keep hitting the API for it.
localStorage.setItem('cfdConfig', JSON.stringify(allSlots));
return allSlots;
},
function(err) {
console.log(err);
});
};
正如所写,从 localStorage(顶部的 config var)返回的数据与底部的 allSlots 格式相同,但不是在 promise 中,因此控制器不喜欢它。我如何包装或退回它以使其成为承诺?我是否需要通过 $http.get() 调用 localStorage (如果可能的话)?还是其他方式?
谢谢。
【问题讨论】:
标签: javascript angularjs asynchronous promise