Search code examples
angularjsangular-resource

AngularJs convert $http POST to $resource POST


I am looking for an example on how to POST data using $resource. I currently have this working code using $http, but would like to simplify it using $resource.

return $http.post("http://localhost:8080/calculate", JSON.stringify(formData))
               .then(function (response) {
                    if (typeof response.data === 'object') {
                        return response.data;
                    } else {
                        // invalid response
                        return $q.reject(response.data);
                    }
                }, function (response) {
                    // something went wrong
                    return $q.reject(response.data);
                });

I've tried searching around for examples, but have not been able to find any that fit this case.


Solution

  • Define your resource like this:

    angular.module('app')
    .factory('MyResource', function ($resource) {
      return $resource('', {}, {
        'calculate': { method: 'POST', url: 'http://localhost:8080/calculate' }
      });
    });
    

    or this:

    angular.module('app')
    .factory('MyResource', function ($resource) {
      return $resource('http://localhost:8080/calculate', {}, {
        'calculate': { method: 'POST' }
      });
    });
    

    And then you can use it:

    MyResource.calculate({}, JSON.stringify(formData), onSuccess, onError);
    

    With first approach you can define different actions with different urls in single resource (url property), which can be useful sometimes, especially when API which you are using is not unified.

    Second approach is better when you have the same endpoint and various request methods for it (like in regular RESTfull APIs). There you can just define them with different names (like get, update, delete, etc.).

    You can also use resources in a way like:

    var result = MyResource.calculate(JSON.stringify(formData));
    

    It's also possible to get access to internal $promise so you can do some more complicated stuff.

    What's important from my experience is that you should remember about isArray: true property, when your API returns JSON array.

    All details are described here: https://docs.angularjs.org/api/ngResource/service/$resource