【问题标题】:Run a hook before $resource constructs the url?在 $resource 构造 url 之前运行一个钩子?
【发布时间】:2016-01-04 00:41:09
【问题描述】:

我想以编程方式更改路由参数之前 $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"} 的挂钩

【问题讨论】:

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


    【解决方案1】:

    我会说你应该选择 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

    【讨论】:

    • 实际上角度文档说你可以将一个函数传递给params对象中指定的每个值,我认为这绝对是合适的。在我的$resource 配置文件中,我实际上并没有传递任何数据,所以 transformRequest 不能真正做任何事情。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-07
    • 2021-09-19
    • 1970-01-01
    • 2016-09-01
    • 1970-01-01
    • 2021-04-05
    • 1970-01-01
    相关资源
    最近更新 更多