There is a fundamental issue I have encountered while working with routes:
- I have multiple routes defined
- If the user is not authenticated, they are redirected to the login page
The problem lies in the fact that, on the initial display of the web app, the user appears to be correctly redirected in terms of the URI, but the displayed view is incorrect (it shows the default view).
If you prefer to see the issue in action, I've set up a jsbin here. You can view the result here.
Steps to replicate the problem:
- Load the page
- You will see 'needsAuth', indicating that the content of the 'needsAuth' view is displayed even though the URI contains 'login' (which should correspond to the 'login' view)
- Refresh the page
- This time you should see 'login', meaning the content of the 'login' view is displayed
The HTML code:
<!DOCTYPE html>
<html ng-app='app'>
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular-route.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div ng-view>
</div>
</body>
</html>
Below is the javascript code:
var template = '{{vm.text}}';
angular
.module('app', ['ngRoute'])
.config(['$routeProvider', routes])
.controller('needsAuthController', needsAuthController)
.controller('loginController', loginController)
.run(['$rootScope', '$location', registerRedirection]);
function routes($routeProvider){
$routeProvider
.when('/needsAuth', {
controller: 'needsAuthController',
controllerAs: 'vm',
template: template
})
.when('/login', {
controller: 'loginController',
controllerAs: 'vm',
template: template
})
.otherwise({
redirectTo: '/needsAuth'
});
}
function needsAuthController(){
var vm = this;
vm.text = 'needsAuth';
}
function loginController(){
var vm = this;
vm.text = 'login';
}
function registerRedirection($rootScope, $location){
$rootScope.$on('$routeChangeStart', function(event, next){
$location.path('/login');
});
}
Upon initial load, there seems to be a discrepancy between the URI and the displayed content
However, upon refresh, everything functions as intended:
Am I making a mistake somewhere? If so, what is the correct approach to redirect users based on certain conditions?
[Edit]: It seems that Angular 1.2.26 behaves properly in this scenario, unlike Angular 1.3.2