Search code examples
angularjsapipostrequestangular-resource

Using $resource and creating a POST request?


I've been digging at this but cannot figure this one out, here's the simple attempt I've made, I thought this was fine but it seems to still request as get....

this.request = function(url, requestData) {
    return $resource(url, null, {
        post : {
            method : 'POST',
            params : requestData || {}
        }
    });
};

Using it:

this.request('/some/api/url', {data : true}).post();

I can't seem to figure out how to get back a promise object so that I can use the repsonse data....


Solution

  • You want to create your resource like so:

    $resource(url, null, {
        post: {
            method: 'POST'
        }
    });
    

    And then:

    this.request.post(
        requestData,
        function (successResponse) {
            // Do whatever with response
        },
        function (failResponse) {
            // Do whatever with response
        }
    );
    

    This will send a POST request to url with requestData as the body.