从位置变化开始的角度获取路由参数 [英] Angular get route parameters from location change start
问题描述
我的路线设置,像这样:
I have routes setup like so:
app.config(function($routeProvider) {
$routeProvider
//login
.when("/", {
templateUrl : "framework/views/login.html",
controller : "LoginCtrl",
title: "Login",
authenticate: false
})
//dashboard
.when("/dashboard", {
templateUrl : "framework/views/dashboard.html",
controller : "DashboardCtrl",
title: "Dashboard",
authenticate: true
});
});
现在我想重定向的位置变化,如果验证
设置为真正
的路线,但一个<$ C上$ C>会话变量不是真正
。
Now I want to redirect location changes if authenticate
is set to true
on the route but a session variable
is not true
.
例如:
$rootScope.$on("$locationChangeStart", function(event, newURL, oldURL){
if (toState.authenticate && $window.sessionStorage.isLoggedIn) {
$location.path("/");
}
});
这工作,如果我使用 $ routeChangeStart
代替,但我简要地看到未来的路由重定向之前。位置的改变似乎停止了,但我不能工作了如何访问路由参数(即身份验证参数)。
This works if I use $routeChangeStart
instead, but then I see the next route briefly before it redirects. Location change seems to stop that, but I can't work out how to access the route parameters (i.e. the authenticate parameter).
我如何做到这一点?还是有更好的办法完全?
How do I do this? Or is there a better way entirely?
推荐答案
正如我在评论和库珀的需求说明
我张贴一个例子:
As I stated in the comment and on demand of Cooper I post an example:
angular.module('myApp',[])
.factory('httpInterceptor', ['$q', '$location',function ($q, $location) {
var canceller = $q.defer();
return {
'request': function(config) {
// promise that should abort the request when resolved.
config.timeout = canceller.promise;
return config;
},
'response': function(response) {
return response;
},
'responseError': function(rejection) {
if (rejection.status === 401) {
canceller.resolve('Unauthorized');
$location.url('/user/signin');
}
if (rejection.status === 403) {
canceller.resolve('Forbidden');
$location.url('/');
}
return $q.reject(rejection);
}
};
}
])
//Http Intercpetor to check auth failures for xhr requests
.config(['$httpProvider',function($httpProvider) {
$httpProvider.interceptors.push('httpInterceptor');
}])
.config(['$stateProvider',function($stateProvider) {
// states for users
$stateProvider
.state('users', {
abstract: true,
templateUrl: 'users/views/users.html',
resolve: {
issessionedin: function(Sessions){
return Sessions.isLoggedIn();
}
}
})
.state('users.account', {
url: '/user/account/:id',
templateUrl: 'users/views/account.html',
resolve: {
user: function(Users, $stateParams){
return Users.get($stateParams.id);
}
},
controller:'UserAccountController'
})
}])
.factory('Sessions', ['$http',
function($http) {
return{
isSessionedIn :function() {
$http.get('/api/v1/issessionedin');
},
isLoggedIn :function() {
$http.get('/api/v1/isloggedin');
},
hasAccess :function(permission) {
$http.get('/api/v1/hasaccess/'+permission);
}
};
}
]);
当然你需要code服务器端返回的HTTP状态code
of course you need the code server side to return the http status code
这篇关于从位置变化开始的角度获取路由参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!