在$ routeProvider中干掉解析参数

时间:2015-05-18 20:07:16

标签: javascript angularjs dry route-provider

什么是" Angular"在干燥路径的解析参数时," / A"和" / B"?在我的$ routeProvider中,我为这些场景调用了完全相同的resolve函数,并且不知道避免在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: '/' 
        });
    }
]};

1 个答案:

答案 0 :(得分:1)

在您的情况下,

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