Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular service, $http.get() with a route param?

Tags:

angularjs

Typically when asking the API endpoint for JSON, I'd 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 user number one. But I want it to be dynamic based on the logged in user.

like image 582
Billy Assim Avatar asked Jan 20 '26 11:01

Billy Assim


1 Answers

You can use the $resource factory instead of using $http. As stated in the documentation $resource is:

A factory which creates a resource object that lets you 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;
});

Usage:

.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);
   });
});
like image 149
ryeballar Avatar answered Jan 22 '26 07:01

ryeballar