Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS : How to use one resolve for all the routes of my application

Tags:

angularjs

I would like to resolve the promise that loads the current user for all the pages of my application. Currently I repeat the resolve in every $routeProvider.when() of my routes.

  $routeProvider.when('/users/edit/:userId', {   templateUrl: 'app/app/assets/partials/user-edit.html',    controller: 'UserEditController',   resolve:{       'currentUser':function( UserService){                     return UserService.getCurrentUser();       }   }   });      $routeProvider.when('/staff_profil/edit', {   templateUrl: 'app/app/assets/partials/profil-edit.html',    controller: 'ProfilEditController',   resolve:{       'currentUser':function( UserService){                     return UserService.getCurrentUser();       }   }  }); 

My goal is to resolve my current user for all the routes without repetition.

like image 600
FlavienBert Avatar asked Nov 12 '13 19:11

FlavienBert


People also ask

How does the AngularJS application route?

Application routes in AngularJS are declared via the $routeProvider, which is the provider of the $route service. This service makes it easy to wire together controllers, view templates, and the current URL location in the browser.

What does resolve property does in route configuration?

Resolve is a property on the routing configuration, and each property on resolve can be an injectable function (meaning it can ask for service dependencies). The function should return a promise.

Which function is used to set up a default route in AngularJS?

We use the ngRoute config() to configure the $routeProvider. The config() takes a function which takes the $routeProvider as parameter and the routing configuration goes inside the function.

What is the use of resolve object in routing?

Resolvelink A data provider class can be used with the router to resolve data during navigation. The interface defines a resolve() method that is invoked right after the ResolveStart router event. The router waits for the data to be resolved before the route is finally activated.


1 Answers

For completeness, here is the whole solution, using angular instead of underscore, with a chainable 'when'. Nothing new in this code, just combined a bunch of the answers above.

var originalWhen = $routeProvider.when;      $routeProvider.when = function(path, route) {         route.resolve || (route.resolve = {});         angular.extend(route.resolve, {             CurrentUser : function(User) {                 return User.current();             }         });          return originalWhen.call($routeProvider, path, route);     }; 
like image 145
Jordan Lapp Avatar answered Oct 23 '22 12:10

Jordan Lapp