Search code examples
javascriptangularjsngresourceangularjs-resourceangularjs-http

Run a hook before $resource constructs the url?


I want to programatically alter route parameters before $resource constructs the url. I cannot use angular's http interceptor to do this, since the route is already concatenated at that point.

Given an Assortment.model.js

module.exports = function($resource) {
    return $resource("", {}, {
        get: {
            url: "/assortment/:model/:id",
            method: "GET",
            params: {id: "@id", model: "@model"} //< this needs to be uppercase
        }
    });
};

...and some controller.js

["Supplier", function(Supplier) {
    Supplier.Assortment.get({ id: 5, model: "user" })
}]

How can I enforce a hook that will always convert {model: "user"} to {model: "User"}


Solution

  • I'd say that you should go for tranformRequest over the $resource get part.

    Code

    module.exports = function($resource) {
      return $resource("", {}, {
        get: {
          url: "/assortment/:model/:id",
          method: "GET",
          params: {
            id: "@id",
            model: "@model"
          },
          transformRequest: function(data, headers) {
            //here you could have the transformation of parameters
            console.log(data);
            return data;
          },
        }
      });
    };
    

    Reference answer here but you should keep the transform request part in $resource's get.