我正在使用会话存储来存储我的应用程序状态。我有一个初始状态,看起来像这样:
appState = {
titles :['Mr', 'Ms', 'Mrs', 'Miss', 'Dr'],
addresses : [],
labels : []
}
这个'appState'是使用$ sessionStorage.appstate保存的。加载应用程序时,需要填充appState的'labels'数组。
我通过运行块angular.module('app')中的$ get请求来执行此操作.run(... populate appState);然后返回我的标签,然后将这些标签保存到sessionStorage以供应用程序使用。
在我的控制器中,当我第一次加载应用程序时尝试从$ sessionStorage访问appState.labels时,标签仍然没有填充,并且我没有显示绑定标签的内容。如果我刷新页面,然后从sessionStorage加载它们,一切正常。
现在(我相信)的原因是绑定发生在我的$ get解决之前所以我的appState.labels仍然是空的。在实际绑定数据之前,如何在$ get标签完成之前将我的应用程序“加载并等待”?
我已经读过我应该在运行块中放置初始化代码。
假设您希望在站点加载之前首先获取数据,最好的方法是使用手动引导,首先获取数据,然后加载应用程序。为此你需要做一些事情:
ng-app="myApp"
文件中删除index.html
,因为我们想根据我们的$http
响应承诺初始化此应用程序。app.js
(function() {
var initInjector = angular.injector(['ng']);
var $http = initInjector.get('$http');
$http.get('/get_label_details/',{headers: {'Cache-Control' : 'no-cache'}}).then(
function (response) {
angular.module('myApp.labels', []).constant('LABELS', response.data);
// manually bootstrapping
angular.element(document).ready(function() {
angular.bootstrap(document, ['myApp']);
});
}
);
})();
myApp.labels
模块时使用myApp
模块,该模块基本上附加到index.html的文档对象。如下所示:
var mainApp = angular.module('myApp',['myApp.labels']);
mainApp.run(function(LABELS){
console.log(LABELS); // you have it here at the run phase
})
所以你最后的app.js
看起来像
(function() {
var initInjector = angular.injector(['ng']);
var $http = initInjector.get('$http');
$http.get('/get_label_details/',{headers: {'Cache-Control' : 'no-cache'}}).then(
function (response) {
angular.module('myApp.labels', []).constant('LABELS', response.data);
angular.element(document).ready(function() {
angular.bootstrap(document, ['myApp']);
});
}
);
})();
var mainApp = angular.module('myApp',['myApp.labels']);
mainApp.run(function(LABELS){
console.log(LABELS); // you have it here at the run phase
})
我最终使用路由解析,等待在实例化控制器之前解析承诺。感谢您的投入!
const RouteConfig = ($stateProvider) => {
'ngInject';
// HOME
$stateProvider
.state('app.root', {
url: '/',
abstract: true,
controller: 'HomeCtrl',
controllerAs: '$ctrl',
templateUrl: 'home/index.html',
resolve:{
store: StoreService => {
console.log('Resolving store...');
// Waits to resolve promise before instantiating controller.
return StoreService.asyncCreateStore();
}
}
})
}