Spinner loading on routechangestart with Authentication library
-
21-12-2019 - |
Question
I'm using the Hot Towel angular library (https://github.com/johnpapa/hottowel-angular-bower) on a project I inherited from a senior developer.
I'm also incorporating Auth0's authentication library for Angular.
I need to restrict some routes to authenticated users. To do that, I set some route properties.
isLogin: true
for routes which is restricted to non-authenticated users.
requiresLogin: true
for routes needing authentication, and the opposite for those who don't. In order to check these properties on each runthrough, I use $rootScope.$on('$routeChangeStart' function())
.
app.run(function ($rootScope, $location, auth, common, config) {
var getLogFn = common.logger.getLogFn,
log = getLogFn('auth handle'),
events = config.events;
$rootScope.$on('$routeChangeSuccess', function (e, nextRoute, currentRoute) {
if (nextRoute.$$route && nextRoute.$$route.settings && nextRoute.$$route.settings.requiresLogin) {
if (!auth.isAuthenticated) {
$location.path('/login');
log('User not authenticated');
}
}
if (nextRoute.$$route && nextRoute.$$route.settings && nextRoute.$$route.settings.isLogin) {
if (auth.isAuthenticated) {
$location.path('/');
log('User is authenticated');
}
}
})
});
Now, it seems this is interfering with the spinner functionality included with Hot-Towel. In Shell.js I find the following:
$rootScope.$on('$routeChangeStart',
function (event, next, current) { toggleSpinner(true); }
);
$rootScope.$on(events.controllerActivateSuccess,
function (data) { toggleSpinner(false); }
);
$rootScope.$on(events.spinnerToggle,
function (data) { toggleSpinner(data.show); }
);
What happens is that the spinner never stops spinning (e.g. vm.isBusy = true because a controller is never activated and resetting this), how would I work around this?
Solution
One idea is that you could use an event ($broadcast) to notify when the un authorized access is made so it is then received by the controller that turns off the spinner.
OTHER TIPS
I haven't studied your code for very long but shouldn't you use $routeChangeSuccess
to stop the spinner?
$scope.isViewLoading = false;
$scope.$on('$routeChangeStart', function() {
$scope.isViewLoading = true;
});
$scope.$on('$routeChangeSuccess', function() {
$scope.isViewLoading = false;
});