我们很快就会对Angular Style Guide进行重构。指南本身非常好(可以在整个网站上找到稍微修改的内容),但没有人提及$资源如何适合工厂,或者没有提到可能被忽略的任何原因。一位指导对use $resource over $http where you can说,但不会将其添加到他们的工厂样式中:/。
我记得在很多地方阅读的资源更好,这就是为什么我开始使用它,但现在我忘记了为什么,并想知道如果这仍然是真的 - 尤其是考虑到这个底部的资源对象帖子。有一些意见(Papas own和again)关于$ resource(不是?)很好,但这是我重新检查的另一个问题。
因此,假设我们要使用$ resource并在下面给出这个示例代码,那么$ resource适合在哪里,以便它遵守指南中样式背后的推理?另外,如果你的答案是“它不会,风格[巧妙]推荐$ http,因为bla,bla和bla。”,那么这也会很有用。现在
(function() {
'use strict';
angular
.module('myModule')
.factory('oneService', oneService);
predicateService.$inject = ['twoService', 'anotherService'];
/* @ngInject */
function oneService(twoService, anotherService) {
var service = {
doSomething: doSomething,
etc: etc
};
// pos 1 (it really only works here but can be LONG)
// var fancyResource = $resource('/path/to/thing', '...');
// Ideally, this should be kept close to the top, right?
return service;
// pos 2 (here or below ////// is cleaner, but doesn't work)
// var fancyResource = $resource('/path/to/thing', '...');
////////////////
function doSomething() {}
// rest of functions here etc...
}
})();
,我们使用$资源的唯一的地方(也许这也是不正确的),就像doSomething()
方法中。在过去的不同时间点,甚至在我们今天的代码中的各个地方,fancyResource
都由服务公开,并直接从控制器使用:oneService.fancyResource.get()
。我认为这可能是$resource
的预期用途,但我不再确定。
另外,考虑一个服务可能会相当大(不要担心其中一些应该/可以分解为多个资源;假设这个大小很可能需要资源对象,并且需要很多动词):
var userResource = $resource(baseApiPath + 'users', {}, {
get: {
method: 'GET',
headers: utilityService.getHeaders('sampling'),
isArray: true,
transformResponse: function(response){
response = JSON.parse(response);
if(response.result){
return response.result.users;
}
return response;
}
},
getUserDetails: {
method: 'GET',
url: baseApiPath+'users/:userId',
params: {
userId: '@userId'
},
headers: utilityService.getHeaders('sampling'),
transformResponse: function(response){
response = JSON.parse(response);
if(response.result){
return response.result.user;
}
return response;
}
},
getUserByRole: {
method: 'GET',
url: baseApiPath+'users/roles/:roleId',
params: {
roleId: '@roleId'
},
headers: utilityService.getHeaders('sampling'),
},
getLoggedInUserData: {
method: 'GET',
url: baseApiPath + 'users/userData',
headers: utilityService.getHeaders('sampling'),
},
getGrantedAuth: {
method: 'GET',
url: baseApiPath+'users/applicationPermissions/userId/:userId/:applicationId/',
params: {
applicationId: '@applicationId',
userId: '@userId'
},
headers: utilityService.getHeaders('sampling'),
}
});
这个答案(http://stackoverflow.com/a/35212885/2800116)正在帮助我为什么$资源可能只是简单的矫枉过正。考虑它,我甚至不使用它提供的save/update/delete()方法,并且不断重做路径。最后一行尤为重要。无论如何,我仍然想知道$ resource对象在上述工厂类型中的位置。 – coblr
似乎你正在推翻事物以及在当前的方法中创建大量的代码重复 – charlietfl