在$ resource构造url之前运行一个钩子?

时间:2015-12-29 06:39:55

标签: javascript angularjs ngresource angularjs-resource angularjs-http

我想在 $ resource构造url之前以编程方式更改路由参数。我不能使用angular的http拦截器来执行此操作,因为此时路由已经连接。

鉴于 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
        }
    });
};

...和一些 controller.js

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

如何强制执行始终将{model: "user"}转换为{model: "User"}

的挂钩

1 个答案:

答案 0 :(得分:2)

我要说你应该tranformRequest获得$resource部分。

<强>代码

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;
      },
    }
  });
};

参考answer here但您应该将转化请求部分保留在$ resource的get中。