0

难以将服务注入另一个服务。我想要一个服务层次结构,为了简洁和封装,我可以向/从父服务传递/请求逻辑。

所以举个例子,我有一个userService,我想让userService管理用户的toDoList。所以我创建了一个 toDoService,我希望控制器通过将请求传递给 userService 来为用户添加一个 toDo,该 userService 中继到 toDoService。这是我所拥有的:

// app.js
angular.module('myApp', [
    // other dependencies...
    'myApp.myServices'
]);

// services/toDoService.js
angular.module('myApp.myServices', [])
       .factory('toDoService', function($http) {

           getStuff = function(userId) {
                // returns $http call
           };

           addStuff = function(userId, data) {
                // returns $http call
           };
});

// services/userService.js
angular.module('myApp.myServices', [])
       .factory('userService', 
         ['$http', 'toDoService', function(
           $http,   toDoService) {

            addToDo = function(data) {
                toDoService.addStuff(user.uid, data)
                     .then(function(success) {
                         // apply bindings
                     })
                     .catch(function(error) {
                         // display error
                     });
            };

            getToDos = function(data) {
                toDoService.getStuff(user.uid)
                     .then(function(success) {
                         // apply bindings
                     })
                     .catch(function(error) {
                         // display error
                     });
            };
}]);

控制器与 userService 一起工作,而 toDoService 中的代码在它最初位于 userService 时工作。但是当我创建 toDoService 并将该代码移到那里并封装它时,角度抱怨 toDoService。

错误:[$injector:unpr] 未知提供者:toDoServiceProvider <- toDoService <- userService

我检查了脚本引用,并且所有脚本都正确包含。例如<script src='/[..]/toDoService.js' />等...

所以我想知道是否可以将服务注入同一模块中的另一个服务?我的命名约定有问题吗?

4

1 回答 1

1
angular.module('myApp.myServices', [])

userService.js 中的这一行定义了模块myApp.services,覆盖了之前在toDoService.js.

只定义一次模块(在单独的文件中)。获取对这个先前定义的模块的引用

angular.module('myApp.myServices')

即没有空数组作为第二个参数。

于 2016-03-04T19:18:19.227 回答