[英]Fetch server settings after boostrap but before anything else
I've been searching for an answer for this but haven't got any unambiguous or clear answer on how to solve and come about this. 我一直在寻找答案,但是对于如何解决和实现这一目标并没有任何明确或明确的答案。
In my anguarJS app, I want to make sure that the very first thing after AngularJS has been loaded / bootstrapped, it goes to the server via $http
and fetch some settings (by called the api: /api/settings/get
) - depending on the subdomain and/or if there is a JWT or other user-session it will retrieve some setting data which should be added to the $rootScope
. 在我的anguarJS应用中,我想确保AngularJS加载/引导后的第一件事是通过
$http
到达服务器并获取一些设置(通过api: /api/settings/get
)-取决于在子域上和/或如果有JWT或其他用户会话,它将检索一些设置数据,这些数据应添加到$rootScope
。
My problem has been that I haven't been able to "halt" the app and only continue it's everyday life when and only when the settings has been fetched and populated the $rootScope
. 我的问题是,我无法“停止”该应用程序,仅当已获取设置并填充
$rootScope
时,才能继续其日常生活。 If the fetch or settings call might fall the app should "stop" - so it's crucial that these settings is loaded very early so I know that everything (services, controllers, directives, etc.) has access to them. 如果获取或设置调用可能会失败,则应用程序应“停止”-因此至关重要的是,必须尽早加载这些设置,以便我知道所有内容(服务,控制器,指令等)都可以访问它们。
I've tried with $broadcast
event and put it into my .run
function in angular but it seems to still resolve the app (perhaps obviously because it's async). 我已经尝试过
$broadcast
事件,并以角度将其放入我的.run
函数中,但它似乎仍可以解析该应用程序(也许显然是因为它是异步的)。
apiConnector.get('api/settings/get').then(function(settings) {
$rootScope.settings = settings;
$rootScope.$broadcast('settings-fetched');
});
However, I don't like this approach and requires me to listen for this event everywhere. 但是,我不喜欢这种方法,并且要求我到处收听此事件。
My routes are both public and restricted. 我的路线既是公共路线又是受限路线。
I hope someone can help me in the right direction of how I would solve this. 我希望有人能在正确的方向帮助我,以解决该问题。
Since you're using ui-router I suggest using resolve before entering your default state: https://github.com/angular-ui/ui-router/wiki#resolve 由于您使用的是ui-router,因此建议您在进入默认状态之前使用resolve: https : //github.com/angular-ui/ui-router/wiki#resolve
Example route configuration from the ui-router docs: ui-router文档中的示例路由配置:
$stateProvider.state('myState', {
resolve:{
// Example using function with returned promise.
// This is the typical use case of resolve.
// You need to inject any services that you are
// using, e.g. apiConnector in this example
settingsObj: function(apiConnector){
return apiConnector.get('api/settings/get');
}
}
If this get fails you can handle this in the resolve by using .then()
to redirect user away from app or w/e. 如果此操作失败,则可以使用
.then()
将用户重定向到远离应用或w / e的位置,以解决此问题。 As with usual promises in angular. 和通常的承诺一样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.