Search code examples
angularjsangular-resource

How to make the URL of $resource generic?


I am new to AngularJS and I have a question here.

I am using $resource for my CRUD actions.

I currently have the code like this,

angular.module("dopAngular.services")
.factory("UserRoleService", ["$resource",
    function ($resource) {
        return $resource("api/UserRoleApi", {}, {
            query: { method: "GET", isArray: true },
            create: { method: "POST" },
            get: { method: "GET" },
            remove: { method: "DELETE" },
            update: { method: "PUT" }
        });

    }]);

    //below is the code in my controller
              UserRoleService.query(function (data) {
                vm.UserRoleLookups = data;
            });

I would like to make my UserRoleService generic, which means I don't want to provide the specific URL for the API in the factory level.

I now modify my code a little bit,

angular.module("dopAngular.services")
.factory("UserRoleService", ["$resource",
    function ($resource, url) {
        return $resource(url, {}, {
            query: { method: "GET", isArray: true },
            create: { method: "POST" },
            get: { method: "GET" },
            remove: { method: "DELETE" },
            update: { method: "PUT" }
        });

    }]);

My question is what I should do in my controller?


Solution

  • So, instead of directly returning $resource, we can encapsulate it with a function that accepts url as a param.

    Something like this:

    myApp.factory('UserRoleService', function($resource) {
      return {
        query: function(url) {
          return $resource(url, {}, {
            query: {
              method: "GET",
              isArray: true
            },
            get: {
              method: "GET"
            }
          });
        }
      }
    });
    

    Now, in controller, you can call it like:

    UserRoleService.query('//httpbin.org').get()
    

    example fiddle