我有角度应用
<body ng-app="appName">
<div class="container" ng-view=""></div>
我有路线
$routeProvider
.when('/', {
templateUrl: 'partials/main',
controller: 'MainCtrl'
})
.when('/login', {
templateUrl: 'partials/login',
controller: 'LoginCtrl'
})
我想在每条路线前拨打电话。比如说如果我没有加载配置文件数据我想要加载配置文件数据并将其存储在$ rootscope中。我该怎么做?
答案 0 :(得分:2)
您可以使用$route's
resolve属性来调用将在路由更改之前执行的函数:
来自AngularJS API文档:
resolve - {Object.<string, function>=} - An optional map of dependencies which should be injected into the controller. If any of these dependencies are promises, the router will wait for them all to be resolved or one to be rejected before the controller is instantiated. If all the promises are resolved successfully, the values of the resolved promises are injected and $routeChangeSuccess event is fired. If any of the promises are rejected the $routeChangeError event is fired. The map object is:
这通常是为了给路线的控制器注入额外的参数,但没有理由你可以做更多的事情。
$routeProvider
.when('/login',{
templateUrl : 'partials/login',
controller: 'loginCtrl',
resolve : {
some_extra_controller_param : ['$route','someService',function($route,someService){
// do stuff here that you would feel necessary to have done prior to route change
someService.doSomething();
return true; // or return an object of data maybe your controller could use
]}
}
});
当然some_extra_controller_param
会作为最后一个参数注入您的控制器,所以请确保您在解析中返回一些内容,loginCtrl
可能如下所示:
.controller('loginCtrl',['$scope','some_extra_controller_param',function($scope,some_extra_controller_param){
...
]});
编辑:您可能希望设置解析功能以使用promises
,因为路由的控制器将等待承诺被解析&#34;在实例化控制器之前。
修改强>
var myBeforeRouteCheck = {
something_to_be_resolved : ['$route','someService',function($route,someService){
// assuming your service runs some kind of function that returns a promise
return someService.someFunc().then(
function(data){
...do successful things...;
return somethingToInjectedParam;
},
function(){
... error ...
return false;
});
}]
};
然后在你的路线中:
.when('/login',{
...
resolve: myBeforeRouteCheck
}