3

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.

1 Answer 1

3

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);
   });
});
Sign up to request clarification or add additional context in comments.

1 Comment

I know :P was waiting for the time limit. Thanks again

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.