New Toronto Group
 - New Toronto Group


| Posted on September 23th, 2015 by Alain Thibodeau

I wanted to share a helpful AngularJS component that has helped me in the past; perhaps it can also help you one day. In the last year I worked on AngularJS applications that required me to get data from the server before bootstrapping the application.

In both cases, I needed to get the logged in user’s roles so I could configure the routes that the user was allowed to see, angular-deferred-bootstrap did the trick.

Referring to its documentation, angular-deferred-bootstrap explains that it waits for a promise to be resolved and then creates a constant from the response. This constant is then available to us in the config or our application.

To start off, we need to call angular-deferred-bootstrap. In my case I have it set up in my index page. Be sure to remove the ng-app directive if you have it. 

       element : document.getElementsByTagName("html")[0],
       module : 'app',
       resolve : {
               USER : ['$http', function ($http) {
                      return $http.get('/userInfo');

We need to tell angular-deferred-bootstrap on which element to bootstrap the application, in my case the element is the html tag. Next, specify the module of the application to load, which is ‘app’. Lastly, specify a promise and the name of the constant we will be using. Above you will see that I declared a USER constant which is given the result of my /userInfo service call. This service returns an object like this:

firstName: "Alain"
lastName: "Thibodeau"
roles: ['admin', 'user','guest']

Heading over to my config, I can now use my newly created constant with the user info.  

var app = angular.module('app', ['ngRoute'])
      .config(['$routeProvider', 'USER', function ($routeProvider, USER) {
  //access to USER here

At this point I can start restricting my routes whichever way I need. I can also inject my newly created USER anywhere in the app as needed.

Head on over to the angular-deferred-bootstrap page and check out some of the advanced features. Loading indicators, error handling and custom injector modules could also be very handy.

Until next time, happy coding!

Posted in AngularJS  | Comments (0)

Comments (0)

Add a Comment

To use reCAPTCHA you must get an API key from

Allowed tags: <b><i><br>Add a new comment: