I want to check an http services to see if a user is authenticated and if it has permission to see the certain page (controller) in AngularJS 1.2.0rc1.
I have this scenario: User A wants to visit http://www.example.com/content. Now this content should not be accessible when he or she is not authenticated. If the user is not authenticated, they should be redirected to http://www.example.com/login.
Now I managed to do this, but I see the rendered html of the content page briefly. I don't want this. How do I redirect to the login page, without rendering the content page?
I register my routes as such:
$routeProvider.when('/login', route.resolve('Login', false))
$routeProvider.when('/content', route.resolve('Content', true))
Now I've tried this:
$rootScope.$on('$routeChangeStart', function (event, route) {
if (route.requiresLogin) {
$http.get('/api/user/loggedin/').then(function (response) {
if (response !== 'true') {
$location.path('/login');
}
});
}
});
Which works, but I still see the content of the html of the other page (content) flashing.
I've read that here that you can also try to change the resolve functionality when the route is resolved:
var resolve = function (baseName, requiresLogin) {
var routeDef = {};
var dependencies = [routeConfig.getControllersDirectory() + baseName + 'Controller.js'];
routeDef.templateUrl = routeConfig.getViewsDirectory() + baseName.toLowerCase() + '.html';
routeDef.controller = baseName + 'Controller';
routeDef.requiresLogin = requiresLogin;
routeDef.resolve = {
load: ['$q', '$rootScope', '$http', '$location', function ($q, $rootScope, $http, $location) {
console.log(requiresLogin);
if (requiresLogin) {
return checkLoggedIn($q, $rootScope, $http, $location);
} else {
return resolveDependencies($q, $rootScope, dependencies);
}
}]
};
return routeDef;
}
But here the page is also displayed briefly.
Hope that you can help me out.