0

How can I convert the following code service that uses $resource to use $http?

angular.module('myApp')
    .factory('MyService', function ($resource) {
        var url = "..";
        return $resource("", {},
            {
                'servizio1': { method: "GET", url: basePath },
                'servizio2': { method: "POST", url: url, data: {} },
                'servizio3': { method: "POST", url: url, data: {} } 
            }
    });

Thanks in advance.

user3423568
  • 741
  • 1
  • 6
  • 4
  • Why do you have to do that? Using $resource is preferred to $http – Khanh TO Mar 22 '14 at 11:04
  • In my Controller I call the service with the following code: (new MyService()).$servizio1() .then(function (data) { }, function (error) { }) .finally(function () { }); – user3423568 Mar 22 '14 at 11:06
  • @KhanhTO why Using $resource is preferred to $http? – Poyraz Yilmaz Mar 22 '14 at 11:41
  • http://stackoverflow.com/a/17668516/3085821 – Sentenza Mar 22 '14 at 11:54
  • @wickY26: using $resource conforms with RESTful design which has benefits http://stackoverflow.com/questions/2191049/what-is-the-advantage-of-using-rest-instead-of-non-rest-http, http://stackoverflow.com/questions/5320003/why-we-should-use-rest . We only use $http when we have to work with legacy APIs not supporting REST – Khanh TO Mar 22 '14 at 12:32

1 Answers1

0

First to your question, try something like:

angular.module('myApp')
   .factory('MyService', function ($http) {
       var url = "..";
       var basePath = "...";
       return {
               servizio1: function(){ return $http.get(basePath); },
               servizio2: function(data){ return $http.post(url, data); } 
           }
   });

Call it with:

var returnValue = (new MyService()).servizio1.then(function(data){...})

But actually you could also use the $resource API and do something like:

angular.module('myApp')
.factory('MyService', function ($resource) {
    var url = "..";
    return $resource(url,{}, {
        saveIt: {
            method: 'POST',
            params: {url: basePath}
    }
});

adn call this with

MyService.get({}, function(data){...});
MyService.saveIt({}, postData, function(){success...}, function(){error...});

Check out AngularJS docs for more

Sentenza
  • 1,269
  • 11
  • 24