Indeed, I have completed a rather straightforward task. For more information, you can view this plnkr.
In my implementation, userHttpService
typically encapsulates $http
, but since there is no actual endpoint to connect to, I am simulating a promise using the $q
library.
The routeConfig
provider allows for configuration of routes during setup. If utilizing something like ui router, a more elegant approach can be achieved with a settings
object in the route setup. For a more advanced example, take a look at this repository.
The configuration looks as follows:
app.config(function($routeProvider, $locationProvider, routeConfigProvider) {
$routeProvider.when('/home', { template: '<h2>Home</h2><p>Please do something</p>' })
$routeProvider.when('/login', { controller: 'LoginController', template: '<h2>Login</h2><div><p><span>Name:</span><input type="text" ng-model="name" /></p><p><span>Password:</span><input type="password" ng-model="password" /></p></div><div><p><button type="submit" ng-click="login()">Login</button></p></div><div><p>{{error}}</p></div>' });
$routeProvider.when('/profile', { controller: 'ProfileController', template: '<h2>Profile</h2><div><p><span>Name:</span>{{name}}</p></div>' });
$routeProvider.otherwise('/home');
$locationProvider.html5Mode(true);
routeConfigProvider.addRouteWhenLoggedIn('/profile');
routeConfigProvider.addRouteWhenLoggedIn('/home');
routeConfigProvider.addRouteWhenLoggedOut('/home');
routeConfigProvider.addRouteWhenLoggedOut('/login');
});
I have consolidated all templates for convenience and used the routeConfigProvider
. Note that when naming it .provider('routeConfig', ...
, you don't need to add Provider
as Angular does it automatically.
Routes are added to different tables based on permissions for logged-in and logged-out users.
Below is the section where route navigation is handled:
app.run(function ($rootScope, routeConfig, userService) {
$rootScope.$on('$routeChangeStart', function (e, c, p) {
var topath = c.$$route.originalPath;
if (userService.isLoggedIn()) {
if (!routeConfig.isAllowedWhenLoggedIn(topath)){
e.preventDefault();
// Redirect using $location.path if needed
}
} else {
if (!routeConfig.isAllowedWhenLoggedOut(topath)){
e.preventDefault();
// Redirect using $location.path if needed
}
}
});
});
This process is relatively simple, involving the use of the userService
to determine user login status and checking against the permission tables to decide whether navigation is allowed.
e.PreventDefault()
is how navigation is prevented.