5

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"}

Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
Daniel Lizik
  • 3,058
  • 2
  • 20
  • 42

1 Answers1

2

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.

Community
  • 1
  • 1
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
  • Actually angular docs say you can pass a function to each value specified in the `params` object, I think that is definitely suitable. In my `$resource` config files I don't actually pass any data so transformRequest can't really do anything. – Daniel Lizik Dec 30 '15 at 00:51