我們很快就會對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