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项目启发。