Angular Services/Factories with $resource
Angular Services/Factories with $resource
我是AngularJS的新Web开发人员。我一直在阅读@toddmotto的Angular styleguide(https://github.com/toddmotto/angularjs-styleguide)。我目前正在构建一个通过RESTful API获取数据的CRUD应用程序。
我有点拘泥于服务和/或工厂。
我以前使用过它(下面的代码),但自从查看了Todd的样式指南后,我想将我的逻辑从控制器转移到服务/工厂,但我不确定在使用新结构之前如何获得它。
有人有什么想法吗?
以前的UserService.js
(function () {
'use strict';
function UserService($resource) {
return $resource('https://api.path.com/users/:id', { }, {
query: {
method: 'GET'
},
create: {
method: 'POST'
},
update: {
method: 'PUT'
},
delete: {
method: 'DELETE'
}
});
}
angular
.module('app')
.factory('UserService', UserService);
})();
目前,我有:
UserController.js
(function () {
'use strict';
function UserController(UserService) {
var _this = this;
UserService
.getUsers()
.then(function (response) {
_this.users = response;
console.table(response);
});
};
}
angular
.module('app')
.controller('UserController', UserController);
})();
UserService.js
(function () {
'use strict';
function UserService($resource) {
var service = {};
service.getUsers = function () {
return $resource('https://api.path.com/users');
};
return service;
}
angular
.module('app')
.factory('UserService', UserService);
})();
编辑
var resource = $resource(baseUrl + '/users/:id', { }, {
query: {
method: 'GET'
},
create: {
method: 'POST'
},
update: {
method: 'PUT'
},
delete: {
method: 'DELETE'
}
});
service.getUsers = function () {
return resource.query().$promise;
};
试试这个:
service.getUsers = function () {
return $resource('https://api.path.com/users').query().$promise;
};
相关文章:
- Fighting with FRP
- issue with FB.Event.subscribe
- geolocation-marker.js conflict with markerclusterer.js
- Angular 2.0 with JavaScript or TypeScript?
- 为什么不推荐使用“with”?是否有更好或其他方法可以“下降”到对象的命名空间
- WebComponentsJS with IE10
- 指令的模板必须只有一个根元素:With restrict E&替换true
- timeago.js with datatable and PHP
- Ajax and Json with Rails
- errors with Javascript try catch
- how to split a string with ','
- Understanding Javascript scope with "var that = this&qu
- Architecture for CPU intensive tasks with NodeJS & Socke
- How to declare a Map containing certain properties with flow
- 设置'这'在React with Inverse Data Flow中
- 可以't通过Angular$resource POST数据
- Unit-testing multiple use cases with Karma & Mocha.js
- Angular.js $resource with ASP.Net webapi?
- Angular Services/Factories with $resource
- $resource angular returning undefined with $promise