Saral
Saral

Reputation: 118

Pass sub params in url http.get AngularJS

I need to GET from a url of this pattern api/v1/album/:albumId/song/:songId/

How do I pass these params in the url.

I tried using params in
params: { albumId: 2, songId: 4 }

but the GET call was made to api/v1/album/:albumId/song/:songId/?albumId=2&songId=4 instead of api/v1/album/2/song/4/

How can this be done without using string concatenation?

Upvotes: 1

Views: 70

Answers (2)

David Tao
David Tao

Reputation: 513

If you use RESTful service, $resource can make this work easier:

More info here: https://docs.angularjs.org/api/ngResource/service/$resource

Example code:

var Song = $resource('/api/v1/album/:albumId/song/:songId/',
                      {albumId: '@albumId', songId: '@songId'});

Song.get({albumId: 2, songId: 4}, function(song) {
    //returned song object

});

//or chaining with promise object
Song.get({albumId: 2, songId: 4})
    .$promise.then(function(song){
    //success handler
    $scope.selectedSong = song;
}, function() {
    //failure handler
});

There are more options depends on your requirement. Hope this can help you :)

Upvotes: 1

Bon Macalindong
Bon Macalindong

Reputation: 1320

Params: { .. } are concatenated on the url as querystring which happened in your case. Simply construct your url having the parameter values included e.g.

var url = 'api/v1/album/1/song/2';
$http.get(url).then(function(){ .... });

Upvotes: 0

Related Questions