我想知道是否有可能在控制器调用任何查询之前使用routeProvider进行解析。
下面是代码片段,它是根据angular教程phonecat
修改的PhoneCatApp.config(['$routeProvider','$httpProvider',
function($routeProvider,$httpProvider) {
$httpProvider.defaults.withCredentials = true;
$routeProvider.when('/phones', {
templateUrl : 'partials/phone-list.html',
controller : 'PhoneListCtrl',
resolve: {
a: function($q,$location){
var def = $q.defer();
def.resolve('a');
$location.path('/login');
return def.promise;
}
}
}).when('/login', {
templateUrl : 'partials/login.html',
controller : 'PhoneDetailCtrl'
}).otherwise({
redirectTo : '/index';
});
});
将我的路由重定向到/login都很好,除了控制器仍然执行来自phoneServices的服务,即Phone.query();
提前感谢您的帮助:)
在你的resolve属性中
resolve: {
a: function($q,$location){
var def = $q.defer();
def.resolve('a');
$location.path('/login');
return def.promise;
}
}
应该是这样的:
resolve: {
a: function($q,$location){
var def = $q.defer();
// process any ajax here
// then evaluate the response if success or fail
if( requestIsSuccessful ) {
def.resolve('a');
} else {
def.reject();
}
return def.promise;
}
}
def.reject()将终止该进程。你可以做一个HTTP拦截器,监听返回的状态码,并重定向到登录页面,如果状态码是401。你也可以搜索HTTP拦截器。在angularjs docs