2014-10-18 91 views
0

我从外部文件注入控制器,我想为外部文件服务做同样的事情。它应该在工厂声明中注册。如何使用AngularJS和RequireJS从外部文件注入服务?

注入控制器工作的

控制器

'use strict'; 

define(['angular', 'services'], function (angular) { 
    return angular.module('vcApp.controllers', ['vcApp.services']) 
     .controller('AuthCtrl', ['$scope', '$injector','AuthService', function($scope, $injector, AuthService) { 
      require(['auth/authCtrl'], function(authCtrl) { 
       $injector.invoke(authCtrl, this, {'$scope': $scope, 'AuthService':AuthService}); 
      }); 
     }]); 
}); 

authCtrl

define([], function() { 
    return ['$scope', '$routeParams', '$location', '$http', 'AuthService', function($scope, $routeParams, $location, $http, authService) { 

     $scope.signIn = function() { 
     ... 
     } 

     $scope.$apply(); 
    }]; 
}); 

现在我要注入服务

服务

'use strict'; 

define(['angular'], function (angular) { 
    angular.module('vcApp.services', []) 
    .factory('AuthService', ['$http', '$injector', function($http, $injector) { 
     require(['auth/authService'], function(authService) { 
      $injector.invoke(authService, this, {'$http': $http}); 
     }); 
    }]); 
}); 

authService

define([], function() { 
    return ['$http', function ($http) { 
     return { 
      login: login 
     }; 

     function login(username, password) { 
      var request = $http(...); 
      return(request); 
     } 
    }] 
}); 

当authController调用authService.login(...),它抛出错误Error: [$injector:undef] Provider 'AuthService' must return a value from $get factory method.

此代码受angular-requirejs-seed项目启发。

回答

2

就像它说的那样,Angular的factory()预计会返回服务对象。您可能有运气的东西,如:

define(['angular'], function (angular) { 
    angular.module('vcApp.services', []) 
    .factory('AuthService', ['$http', '$injector', function($http, $injector) { 
     var stub = {}; 
     require(['auth/authService'], function(authService) { 
      angular.extend(stub, $injector.invoke(authService, this, {'$http': $http})); 
     }); 
     return stub; 
    }]); 
}); 

在这里定义存根为服务和扩展它,当服务实际上是延迟加载。

(顺便说一句,我认为的$injector.invoke()最后2个参数在这种情况下是多余的。)

如果你想另一个想法有关混合RequireJS和角度,与延迟加载和r.js优化打得很好,你可以看看angular-require-lazy

相关问题