我的 previous topic 遇到了问题,我无法使用我的服务。
经过一些研究,我终于找到了一种使用我的服务的方法。我仍然想知道为什么我使用 javascript 对象作为方法容器的其他方法没有成功。我有一些猜测,但找不到合适的解决方案。
希望你们能带领我走上正确的道路。
controller.js(工作解决方案)
angular.module('TodoApp.controllers', []).
controller('listCtrl', function ($scope, $location, todoApiService) {
$scope.todos = todoApiService.query();
});
services.js(工作解决方案)
angular.module('TodoApp.services', []).
factory('todoApiService', function ($resource) {
return $resource('/api/todo/:id', { id: '@id' }, { update: { method: 'PUT' } });
});
controllers.js(无效解决方案)
angular.module('TodoApp.controllers', []).
controller('listCtrl', function ($scope, $location, todoApiService) {
$scope.todos = todoApiService.getMyTodos.query();
});
services.js(无效解决方案)
angular.module('TodoApp.services', []).
factory('todoApiService', function () {
var todoApi = {};
todoApi.getMyTodos = function ($resource) {
return $resource('/api/todo/:id', { id: '@id' }, { update: { method: 'PUT' } });
};
return todoApi;
});
最佳答案
您应该:
将 $resource
注入(inject)您的工厂函数,就像您在工作版本中所做的那样。然后您可以删除 $resource
作为 getMyTodos
的参数。
angular.module('TodoApp.services', []).
factory('todoApiService', function ($resource) {
var todoApi = {};
todoApi.getMyTodos = function () {
return $resource('/api/todo/:id', { id: '@id' }, { update: { method: 'PUT' } });
};
return todoApi;
});
然后从 Controller :
angular.module('TodoApp.controllers', []).
controller('listCtrl', function ($scope, $location, todoApiService) {
$scope.todos = todoApiService.getMyTodos().query();
});
或者,您可以将 $resource
从 Controller 传递到 getMyTodos
(将其注入(inject) Controller 之后) - 这样您的 Controller 就会看起来像:
angular.module('TodoApp.controllers', []).
controller('listCtrl', function ($scope, $location, todoApiService, $resource) {
$scope.todos = todoApiService.getMyTodos($resource).query();
});
我没有检查这是否有效,但它应该:)
关于javascript - AngularJS - 使用 $resource 并与 RESTful 数据源交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24162231/