Reputation: 5637
I'm having the classic problem where the $locationChangeStart
event fires multiple times. I've tried to use the preventDefault
but I can't seem to master this.
Two problems - first scenario uses $location
and the second uses $state
:
$state.go('main')
, however $locationChangeStart
is fired again. I do not want this behavior.$stateChangeStart
event, I basically hit an infinite loop
scenario. Meaning that, when this event fires I check for user authentication
. If the user is NOT authenticated, I then redirect using $state.go('login');
. This causes an infinite loop.Here's my app.js for starters:
(function () {
'use strict';
angular.module('rage', [
'ui.router',
'ui.bootstrap',
'ui.dashboard',
'kendo.directives'
]).run(['$rootScope', '$state', '$location', 'userService', 'loginService', init]);
function init($rootScope, $state, $location, userService, loginService) {
$rootScope.rageSessionVars = {};
$rootScope.$state = $state;
$rootScope.isLoggedin = false; // just something to possibly use ???
$rootScope.$on('$locationChangeStart', function () {
var userToken = loginService.getUserCookie();
// check if cookie expired, then authenticate user !
if (userToken) {
if (!loginService.isUserCookieExpired(userToken)) {
if (loginService.authUser(userToken)) {
$state.go('main');
}
else {
$location.url('index.html#/?login'); // not authenticated !
}
}
}
else {
$state.go('login');
$location.url('index.html#/?login');
}
});
}
})();
I've also created a plunker for a similar scenario yesterday, and simply modified the app.js
to now include the locationChangeStart event.
Online plunker here: http://plnkr.co/edit/hsSrPqFp0hpJ4A8cTsVL?p=preview
Bottom line is I'd like to hook into one of these event for a smooth user Login/Logout experience, but I always end up in a snag with these Angular events.
Thank you in advance for your expert tips.
regards, Bob
Upvotes: 0
Views: 1695
Reputation: 2551
While using angular ui router, use $stateChangeStart
and $stateChangeSuccess
to control actions like authentications and manual routing during state changing.
Upvotes: 1