Angular, $ http.get () with route parameter?

Usually when you ask the API endpoint for JSON, I would write something like this:

factory('User', function($http) {
    return {
        get: function() {
            return $http.get('/api/users');
        }
    }
});

      

However, how can I add a route parameter to get a specific user (RESTful show method)?

i.e. /api/users/1

to get the user number. But I want it to be dynamic based on the logged in user.

+3


source to share


1 answer


You can use factory instead . As the documentation states : $resource

$http

$resource

A factory that creates a resource object that allows you to interact with RESTful server-side data sources.

To do what you want, you can simply declare it like this:



factory('User', function($resource) {
    var UserResource = $resource('/api/users/:id');
    return UserResource;
});

      

Using:

.controller('Ctrl', function($scope, User) {

   // Sends GET /api/users/1
   User.get({id: '1'}).$promise.then(function(user) {
     // expects a single user data object
     console.log(user);
   });

   // Sends GET /api/users
   User.query().$promise.then(function(users) {
     // expects an array of user data objects
     console.log(users);
   });
});

      

+3


source







All Articles