Vee
Vee

Reputation: 1841

DRYing up resolve parameter in $routeProvider

What is the "Angular" way in DRYing up the resolve parameter for the paths, "/A" and "/B"? In my $routeProvider, I call for the exact same resolve function for those scenarios and don't know the best way of avoiding duplicating code in the AngularJS framework.

var app = angular.module("myProject", []);

app.config(["$routeProvider",function($routeProvider) {
    $routeProvider.
        when("/A", {
            templateUrl: "templates/A.html",
            controller: "AController",
            resolve: {
                tokenRefresh: function(serviceA, serviceB){
                    if (serviceA.refreshingToken() == true)
                    {
                        return(serviceB.refresh());
                    }   
                }
            }
        }).   
        when("/B", {
            templateUrl: "templates/B.html",
            controller: "BController",          
            resolve: {
                tokenRefresh: function(serviceA, serviceB){
                    if (serviceA.refreshingToken() == true)
                    {
                        return(serviceB.refresh());
                    }   
                }
            }
        }).
        otherwise({ 
            redirectTo: '/' 
        });
    }
]};

Upvotes: 0

Views: 42

Answers (1)

Justin Niessner
Justin Niessner

Reputation: 245429

resolve in your case is just a JSON object. Why not declare it a single time before your call to $routeProvider?

var resolver = {
    tokenRefresh: function(serviceA, serviceB){
        if (serviceA.refreshingToken() == true)
        {
            return(serviceB.refresh());
        }   
    }
};

$routeProvider.
when("/A", {
    templateUrl: "templates/A.html",
    controller: "AController",
    resolve: resolver
}).   
when("/B", {
    templateUrl: "templates/B.html",
    controller: "BController",          
    resolve: resolver
}).
otherwise({ 
    redirectTo: '/' 
});

Upvotes: 1

Related Questions