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.

5
  • Why do you have to do that? Using $resource is preferred to $http Commented Mar 22, 2014 at 11:04
  • In my Controller I call the service with the following code: (new MyService()).$servizio1() .then(function (data) { }, function (error) { }) .finally(function () { }); Commented Mar 22, 2014 at 11:06
  • @KhanhTO why Using $resource is preferred to $http? Commented Mar 22, 2014 at 11:41
  • stackoverflow.com/a/17668516/3085821 Commented Mar 22, 2014 at 11:54
  • @wickY26: using $resource conforms with RESTful design which has benefits stackoverflow.com/questions/2191049/…, stackoverflow.com/questions/5320003/why-we-should-use-rest . We only use $http when we have to work with legacy APIs not supporting REST Commented Mar 22, 2014 at 12:32

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.