Search code examples
javascriptangularjsangular-routingnormalize

Common route resolver in angularjs?


I am using route resolver in angularjs,for user will be redirect to login if user is not logged in as follows,

 $routeProvider
        .when('/', {
            templateUrl: 'app/components/main/dashboard.html',
            controller: 'dashboardController',
            resolve: {
                login: function ($rootScope, $location) {
                    if (!$rootScope.currentUser) {
                        $location.path('/login');
                    }
                }
            }
        })

Here I want use this login function in many other routes,So i can copy paste same resolve function to every where as follows,

.when('/items', {
            templateUrl: 'app/components/item/list.html',
            controller: 'itemController',
            resolve: {
                login: function ($rootScope, $location) {
                    if (!$rootScope.currentUser) {
                        $location.path('/login');
                    }
                }
            }
        })

It is working fine,my question is,is there any way to avoid this duplication of codes or is there any other better method ?


Solution

  • I set up a github repository yesterday which is a starting point for a web app and contains this feature here

    If you look in public/app/app-routes.js you will see I have added resolve functions as variables, then you can simply do this rather than writing a whole function each time:

    Function

    var checkLoggedIn = function($q, $timeout, $http, $window, $location, $rootScope) {
            // Initialize a new promise
            var deferred = $q.defer();
    
            // Make an AJAX call to check if the user is logged in
            $http.get('/loggedin').success(function(user) {
    
                // Authenticated
                if (user !== '0') {
                    $rootScope.loggedInUser = user;
                    $window.sessionStorage['loggedInUser'] = JSON.stringify(user);
                    deferred.resolve();
                }
    
                // Not Authenticated
                else {
                    $window.sessionStorage['loggedInUser'] = null;
                    $rootScope.loggedInUser = null;
                    deferred.reject();
                    $location.url('/login');
                }
            });
    
            return deferred.promise;
        };
        checkLoggedIn.$inject = ["$q", "$timeout", "$http", "$window", "$location", "$rootScope"];
    

    Route

    .when('/profile', {
                title: 'Profile',
                templateUrl: '/app/templates/profile.html',
                controller: 'ProfileController',
                resolve: {
                    loggedIn: checkLoggedIn
                }
            })
    

    Should be easily adaptable for your app. Hope that helps!