Resolve enables you to specify a series of tasks that must be completed before the route is loaded. It consists of keys and functions, allowing you to perform actions like asynchronous http requests, executing code snippets, setting values, and more before the page loads.
For example, if you have a service that makes an http get request and returns a promise to ensure a session exists on the server every time a route is accessed, resolve ensures that the page will not load until the http request is successful and the promise is fulfilled. If the promise fails to fulfill, the page will not load:
.config([ '$routeProvider', function( $routeProvide ) {
$routeProvider.when('/dashboard', {
templateUrl: 'framework/views/dashboard.html',
controller: 'DashboardCtrl',
controllerAs: 'dashCtrl',
resolve: {
DateOfBirth: ['Date', function( Date ) { // another example of using resolve
return Date.getCurrentYear() - 37;
}],
AuthUser: ['$q', '$location', 'UserSession',
function( $q, $location, UserSession) {
return UserSession.getSession()
.then(function( success ) {
// execute actions when promise is successful
// handle logic here
return success
}, function( error ) {
// execute actions when promise fails
// handle logic here
$location.path('/login);
$location.replace();
return $q.reject( error );
});
}];
}
})
}]);
One advantage of resolve is that the keys are injectable, allowing you to pass the result to your controller:
.controller('DashboardCtrl', ['AuthUser', 'UserSession', 'DateOfBirth'
function(AuthUser, UserSession, DateOfBirth) {
var self = this;
self.status = AuthUser.status;
self.response = AuthUser.data;
}]);
You can then use the resolved data in your UI, displaying errors using dashCtrl.response or dashCtrl.status, knowing that the page has not loaded yet.
I recommend checking the session upon route access instead of storing it on the client side. Additionally, keep in mind that resolve only works with routes. For server calls unrelated to routing, consider using interceptors to monitor outgoing and incoming requests/responses while on specific pages like /dashboard/home without triggering a route change.