Use $resource instead of $http for API calls in AngularJS
When I am teaching new AngularJS developers, I often see these massive $http methods inside of services.
$http.get('http://api.url')
.success(function(res){
// do something massive with res
})
.error(function(err){
// do something errory with the error
})
$http.post('http://api.url')
.success(function(res){
// do something massive with res
})
.error(function(err){
// do something errory with the error
})
ETC...
Instead, it is much more clean and compact if you create a $factory, and create $resource methods as the return.
app.factory('coderWallApi', function($resource){
return: {
'methodName': $resource('http://api.url')
}
})
Five lines to replace 20 -30 if you are handwriting your http calls, and it gives you the opportunity to write very syntactical easy to understand services.
You can use your service to process and store that data, which is a very strong and scaleable design.
app.service('coderWallViewService' , function(coderWallApi){
var service = this;
var init = function(){
coderWallApi.methodName.get(null, function(res){
service.data = res;
// put all of your data processing logic here
})
}
service.controllersCalltoService = function(){
var defer = $q.defer();
if(service.data){
defer.resolve(service.data);
}else {
coderWallApi.methodName.get(null, function(res){
service.data = res;
defer.resolve(res);
})
}
return defer.promise;
}
init();
})Written by Jeremy Stover
Related protips
2 Responses
it should not be coderWallApi.methodName instead coderWallViewService.methodName ?
@korin Yup! Editing now :) Good looking out.
Have a fresh tip? Share with Coderwall community!
AngularJS pages are long-lived browser apps with the same script risk as a newer single-page app. Third-party code in the template can read forms and values rendered on the page.
Security insights from Cside