angularjs - Grouping back-end APIs -
while using angularjs's $http service i've found hard manage urls backend - they're spread around controller's code. they're duplicated. of them in form of $http.get('/api/something').then(...)
.
to put of them different services sounds quite unreasonable: 1 line of code may small modifications (like adding header etc).
other solution putting them constants, in case still use $http.get(apiurls.someurl)
looks little bit verbose...
so question is: best way manage urls back-end?
currently came idea of grouping them servicies , expose them calls $http. here solution: http://plnkr.co/edit/vjqxhbv54bmjkcugj4qx?p=preview
service:
.factory('adminapi', function($http) { var apimap = { 'deleteauth': {url:'/api/oauth/delete',method:'put'}, 'getinvaliduser': {url:'/api/users/invalid',method:'get'}, 'createitem': {url:'/api/items/create',method:'post'} }; var api = {}; var preparecall = function(config) { return function(params) { var requestconfig = angular.copy(config); if (config.method=='get') requestconfig.params = params; else requestconfig.data = params; return $http(requestconfig); }; }; for(var name in apimap) api[name] = preparecall(apimap[name]); return api; });
and in controllers like:
adminapi.deleteauth({data:123}).then(function(result) { // });
in case have abstraction (do not have inject $http
controller), unit-tests become little bit easier (i not have use $httpbackend service, mock service calls).
Comments
Post a Comment