Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS | Set Path Parmeter while using $http.get method

Tags:

angularjs

I have a GET endpoint with URI as /user/user-id . The 'user-id' is the path variable here.

How can I set the path variable while making the GET request?

This is what I tried:-

$http.get('/user/:id',{
                params: {id:key}
            });

Instead of replacing the path variable, the id get appended as query param. i.e my debugger show the request URL as 'http://localhost:8080/user/:id?id=test'

My expected resolved URL should be like 'http://localhost:8080/user/test'

like image 456
Kumar Sambhav Avatar asked Mar 16 '15 13:03

Kumar Sambhav


1 Answers

$http's params object is meant for query strings, so key-value pairs you pass into params are output as query string keys and values.

$http.get('/user', {
    params: { id: "test" }
});

Becomes: http://localhost:8080/user?id=test

If you need http://localhost:8080/user/test, you can either:

  1. Construct the url yourself,

    $http.get('/user/' + id);

  2. Or, use $resource (specifically $resource.get https://docs.angularjs.org/api/ngResource/service/$resource). This is a little cleaner.

like image 173
user2943490 Avatar answered Oct 27 '22 00:10

user2943490