angularjs
2016-01-27 16 views 0 likes 
0

解析函數中有很多相同的代碼。是否有可能對其做出可重用的功能並將其傳遞給解決方案?在路由中解析爲可重用函數

FROM THIS... 

.when('/workers', { 
     resolve: { 
      "check": function() { 
       if (!isLoggedIn() || !isAdmin()) { 
        window.location.href = '#/about'; 
       } 
      }, 
     }, 
     templateUrl: 'html/admin/workers.html', 
     controller: 'adminWorkersController' 
    }) 

    TO SOMETHING LIKE THIS: 

.when('/workers', { 
      resolve: myResolveFunction() 
      templateUrl: 'html/admin/workers.html', 
      controller: 'adminWorkersController' 
     }) 

回答

1

您可以創建路線的決心提供商

var app = angular.module('app', []); 
     //Must be a provider since it will be injected into module.config() 
     app.provider('routeResolver', function() { 
      this.$get = function() { 
       return this; 
      }; 
      this.route = function() { 
       var resolve = function() { 
       // resolve 
       } 
       return {resolve: resolve}; 
      }; 
     }); 

app.config(function(routeResolverProvider) { 
    .when('/workers', { 
      resolve: routeResolverProvider.resolve() 
      templateUrl: 'html/admin/workers.html', 
      controller: 'adminWorkersController' 
     }) 
}) 
1

您可以使用服務作爲可重用代碼。例如:

resolve: { 
    "check": function(yourService) {//inject service 
     yourService.method(); //this method of the service contains reusable code 
    } 
} 
相關問題