AngularJS creating multiple $resource endpoints in a service

So this had me baffled for a bit. For using Angular’s $resource in your Angular service, you map it to a particular URL with (optional) parameters defined for that URL. Then how can you have multiple resources with their own unique URLs mapped in the same service?

For example, here’s a service called User which maps to the URL “/api/users/…”:

angular.module('myApp')
  .factory('User', function($resource) {
    return $resource('/api/users/:id/:controller', {
      id: '@_id'
    }, {
      changePassword: {
        method: 'PUT',
        params: {
          controller: 'password'
        }
      },
      get: {
        method: 'GET',
        params: {
          id: 'me'
        }
      }
    });
  });

As you can see, there’s one resource in this service that maps to the one URL, so then how can I add another URL for the $resource?

The answer turned out to be pretty simple, actually. What you have to do is create an object (JSON) of $resources that are returned for the service. You can have individual elements inside the object that each map to a different $resource. So, for example:

'use strict';

angular.module('myApp')
  .factory('User', function ($resource) {
    return {
      WithId: $resource(
        '/api/users/:id/:controller',
        {
          id: '@_id'
        },
        {
          changePassword: {
            method: 'PUT',
            params: {
              controller: 'password'
            }
          },
        }
      ),
      Misc: $resource(
        '/api/users/misc/:controller',
        null,
        {
          generateResetPasswordToken: {
            method: 'POST',
            params: {
              controller: 'generateResetPasswordToken'
            }
          },
        }
      ),
    };
  });

In the above example, in the “User” service, we have two resources that can be accessed. To access “changePassword”, we can use User.WithId.changePassword (which maps to a particular URL), and to access “generateResetPasswordToken” we use User.Misc.generateResetPasswordToken (which maps to another URL).

Voila!

2 thoughts on “AngularJS creating multiple $resource endpoints in a service”

  1. How do you instantiate a resource when there are two resources in the service ?

    Normally,
    $scope.user = new User();

    would give you an instance and subsequently access to the resource. Doesn’t seem to work with the multiple endpoints. Any ideas?

Leave a Reply

Your email address will not be published. Required fields are marked *