Last Updated: December 15, 2016
·
718
· Kadajett

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();
})

2 Responses
Add your response

it should not be coderWallApi.methodName instead coderWallViewService.methodName ?

over 1 year ago ·

@korin Yup! Editing now :) Good looking out.

over 1 year ago ·