Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - $resource different URL for Get and Post

Tags:

$resource is awesome providing very convenient way to handle web services. What if GET and POST have to be performed on different URLs?

For example, GET URL is http://localhost/pleaseGethere/:id and POST URL is http://localhost/pleasePosthere without any parameter

like image 304
MomentH Avatar asked Sep 28 '12 05:09

MomentH


3 Answers

Use 'url' property of [actions] to override the default url.

$resource(url, [paramDefaults], [actions], options);

for example:

$resource('http://localhost/pleaseGethere/:id',{},{
    getMethod:{
        method:'GET',
        isArray:true
    }
    postMethod:{
        url:'http://localhost/pleasePosthere',
        method:'POST',
        isArray:false
    }
}

Usage of Angular $resource: http://docs.angularjs.org/api/ngResource/service/$resource

like image 75
Iris Wong Avatar answered Oct 17 '22 07:10

Iris Wong


You should be able to expose the URL as a parameter. I was able to do this:

$provide.factory('twitterResource', [
    '$resource',
    function($resource) {
        return $resource(
            'https://:url/:action',
            {
                url: 'search.twitter.com',
                action: 'search.json',
                q: '#ThingsYouSayToYourBestFriend',
                callback: 'JSON_CALLBACK'
            },
            {
                get: {
                    method: 'JSONP'
                }
            }
        );
    }
]);

Then you can overwrite the URL on your GET call.

The one caveat I found during my REALLY brief testing was that if I included http:// in the URL string, it didn't work. I didn't get an error message. It just did nothing.

like image 22
Todd Avatar answered Oct 17 '22 09:10

Todd


If you add the hash with param names into the $resource call:

$resource('localhost/pleaseGethere/:id', {id: '@id'});

Then the :id will be mapped to id param when invoking the function (this will call GET localhost/pleaseGethere/123):

Resource.get({id: 123});

For POST, you simply don't assign the id param:

Resource.post({}, {name: "Joe"});

The proper URL will be called, which is in this case POST localhost/pleaseGethere (the trailing slash is stripped by ngResource).

See http://docs.angularjs.org/api/ngResource.$resource -> Examples -> Credit card resource for more details.

like image 26
Petr Bela Avatar answered Oct 17 '22 09:10

Petr Bela