2

Is it possible to use the AngularJS $http service to parameterize a restful url? For example:

var URL = '/api/countries/:countryId/states'

var getStates = function (countryId) {
    $http.get(URL, { countryId: countryId }).then();
};

Every combination I try ends up using a query string, which is not what I want.

G. Deward
  • 1,352
  • 1
  • 15
  • 27
  • read this http://stackoverflow.com/questions/5216567/is-this-statement-correct-http-get-method-always-has-no-message-body. I suppose angularjs always use query string instead of body when it used the get, method if you change to post, you will see the body – Koitoer Apr 28 '15 at 22:56
  • @G.Deward Try using [$resource](https://docs.angularjs.org/api/ngResource/service/$resource) – Tony Apr 28 '15 at 23:26

4 Answers4

2

I don't think that will be possible in the way that you describe.

In the end you'll probably just want to go with something like the following:

var getStates = function (countryId) {
    var URL = '/api/countries/'+countryId+'/states'
    $http.get(URL, {}).then();
};

Though if someone has a better solution i'd love to hear it :)

Sharn White
  • 615
  • 3
  • 15
  • I must admit, this is rather shocking and disappointing. How can they NOT have a RESTful URL builder in 2015? – G. Deward Apr 28 '15 at 23:08
  • Since @SharnWhite seems curious also, you might be interested in [$resource](https://docs.angularjs.org/api/ngResource/service/$resource) – Tony Apr 28 '15 at 23:33
1

As Rathish and Tony noted, you can use $resource:

var URL = '/api/countries/:countryId/states'

var states = $resource(URL)

var getStates = function (countryId) {
  states.query({ countryId: countryId }).then(...)
};
0

I Think this link will help you AngularJS passing data to $http.get request

I'm on mobile right now but can post an example when I get to a computer

Community
  • 1
  • 1
Mat Wolff
  • 26
  • 3
0

$resource factory lets you build a parameterized URL https://docs.angularjs.org/api/ngResource/service/$resource