In web application, it's common that some pages are only available to logged-in user. This post shows how to restrict certain AngularJS routes to logged-in users. ui-router supports resolve property to check whether a route is resolved.

First we need a function returns promise to check whether a user is logged-in or not.

In the code above, create a deferred object using $q's$q.defer(). If a user object already exists, the deferred is resolved immediately. If not, a HTTP request is sent to server to get current logged-in user's information. If server returns user object, resolve the deferred, otherwise reject the deferred and redirect user to login page.

Then use checkLoggedOut function in ui-router state definition as below.

  url: '/restricted'
  templateUrl: 'restricted.html'
  controller: 'DemoCtrl'
    loggedin: checkLoggedOut

Add checkLoggedOut to all states restricted to logged-in users.