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

Run a hook before $resource constructs the url?

本文关键字:运行 url resource 构造      更新时间:2023-09-26

我想在$resource构造url之前用程序更改路由参数。我不能使用angular的http拦截器来做这件事,因为路由已经在这一点上连接起来了。

给定产品组合.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"} 的挂钩

我认为您应该选择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;
      },
    }
  });
};

请参阅此处的答案,但您应该将转换请求部分保留在$resource的get中。