难以将服务注入另一个服务。我想要一个服务层次结构,为了简洁和封装,我可以向/从父服务传递/请求逻辑。
所以举个例子,我有一个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' />
等...
所以我想知道是否可以将服务注入同一模块中的另一个服务?我的命名约定有问题吗?