Search code examples
javascriptangularjsroutesresolve

Basic resolve for Angular routing


I'm creating a very basic login system with Angular JS. Basically, after a login form is submitted, credentials are checked against a database using PHP and Mysqli. If all is ok, it returns successful and I set a variable like $rootScope.isLoggedIn = true and user details in other similar variables.

Now I'm trying to work out the best way to use resolve with my routes so that only logged in users or users with correct permissions can access a page (including on page reload!)

I just can't get my head around how these resolves work. My routing looks like this so far (the dashboard page needs user to be logged in):

app.config(function($routeProvider) {

  $routeProvider

  //login
  .when('/', {
    templateUrl : 'framework/views/login.html',
    controller  : 'LoginCtrl',
    title: 'Admin Login'
  })

  //dashboard
  .when('/dashboard', {
    templateUrl : 'framework/views/dashboard.html',
    controller  : 'DashboardCtrl',
    title: 'Dashboard',
    resolve: { ? }
  })

  //catch all redirect
  .otherwise({ redirectTo: '/' });

 });

Solution

  • Resolve will open your route with a resolved variable (that can be injected into controller) as soon as it gets value (instantly or when returned promise will be resolved). See:

    resolve: { 
        myVar: function(service, $rootScope, etc){
            return service.obj; // or primitive, or promise or something else
        }
    }
    .controller('DashboardCtrl', function(myVar){
        console.log(myVar); // that service.obj goes here
    }
    

    That can't prevent route from loading (as I understand, please correct me if I'm wrong).

    For your case it's better to use something like this:

    .when('/', {
        templateUrl : 'framework/views/login.html',
        controller  : 'LoginCtrl',
        title: 'Admin Login',
        authenticate: false
    })
    .when('/dashboard', {
        templateUrl : 'framework/views/dashboard.html',
        controller  : 'DashboardCtrl',
        title: 'Dashboard',
        authenticate: true
    })
    
    $rootScope.$on("$routeChangeStart", function(event, toState){
        if (toState.authenticate && !$rootScope.isLoggedIn){
            $location.path('/');
        }
    });