干掉 $routeProvider 中的解析参数

DRYing up resolve parameter in $routeProvider

干涸路径“/A”和“/B”的解析参数的"Angular"方法是什么?在我的 $routeProvider 中,我为这些场景调用了完全相同的解析函数,并且不知道在 AngularJS 框架中避免重复代码的最佳方法。

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: '/' 
        });
    }
]};

resolve 在你的例子中只是一个 JSON 对象。为什么不在调用 $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: '/' 
});