Reputation: 2175
i would like to submit an http request to check if the user is logged in each time a route is changed. is this possible with the latest version of angular ( 1.4.5 ).
my routes are like this:
// configure routes
app.config(['$routeProvider', function($routeProvider){
$routeProvider
// route for the home page
.when('/', {
templateUrl : 'directives/about.html',
controller : 'mainController'
})
// route for the home page
.when('/login', {
templateUrl : 'directives/login.html',
controller : 'loginContoller'
})
// route for the about page
.when('/about', {
templateUrl : 'directives/about.html',
controller : 'aboutController'
})
// route for the contact page
.when('/contact', {
templateUrl : 'directives/contact.html',
controller : 'contactController'
});
}]);
Upvotes: 0
Views: 48
Reputation: 1398
If you look a the docs you will see what arguments the when()
method takes.
The route
agument is an object and one property is called resolve
.
The resolve property is an map of dependencies that should be resolved.
$routeProvider.when('/', {
templateUrl: 'directives/about.html',
controller: 'mainController',
resolve: {
loginCheck: function (myLoginCheckService) {
return myLoginCheckService();//could return a $q.promise object.
}
}
});
resolve
- An optional map of dependencies which should be injected into the controller. If any of these dependencies are promises, the router will wait for them all to be resolved or one to be rejected before the controller is instantiated. If all the promises are resolved successfully, the values of the resolved promises are injected and$routeChangeSuccess
event is fired. If any of the promises are rejected the$routeChangeError
event is fired.
AngularJS Docs
Look at the docs for more information.
Upvotes: 2
Reputation: 1118
Can do it by adding routeChangeStart inside run block of Angularjs
app.run(function($rootScope, $location) {
$rootScope.$on( "$routeChangeStart", function(event, next, current) {
if ($rootScope.loggedInUser == null) {
// no logged user, redirect to /login
if ( next.templateUrl === "partials/login.html") {
} else {
$location.path("/login");
}
}
});
});
Upvotes: 1
Reputation: 11
create a helper method
function auth(configs){
// write your auth code here
return configs;
}
At the router would be like this.
.when('/', auth({
templateUrl : 'directives/about.html',
controller : 'mainController'
}))
Upvotes: 1