I am currently using routeProvider for directing to the different pages, and it works fine with authentication, but needed to add different roles for different users. Most of the answers online point to ui-router, but it would be a hassle to migrate everything to that so is there any way to do this with the basic routeProvider?
1 Answer
This is a small version of what I use in my app:
app.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.when('/admin', {
templateUrl: 'views/admin.html',
controller: 'AdminCtrl',
roles: ['admin']
});
}).run(function ($rootScope, $location, auth) {
$rootScope.$on('$routeChangeStart', function(e, next) {
if(next.roles && !auth.validRoles(next.roles)) {
e.preventDefault();
$location.path('/error-403');
}
});
});
"auth" is a service where my logged user is stored, and the method validRoles check if the user has the role of the view.
2 Comments
Anoop
I am not understanding what you mean by "where my logged user is". If possible, could you set up a plunker or show the service, and the method used. I am new to angular so not that proficient with it.
Facundo Pedrazzini
Look the HackedByChinese answer stackoverflow.com/questions/22537311/…. I inspired on that when I do this. Check the 'principal' services, thats what I talk when i say 'where my logged user is stored'.