【问题标题】:What is a proper way to write an interceptor for the resource?为资源编写拦截器的正确方法是什么?
【发布时间】:2014-08-19 00:09:03
【问题描述】:

我需要在每次获取、保存、更新时转换来自服务的响应。我创建了一个资源并添加了一个可以执行的转换器,但是返回的对象的结构与我不使用转换器时的结构不同。这里我说的是响应的结构,而不是我正在转换的对象。 这是我的资源:

angular.module('app')
   .factory('Insureds', ['$resource', 'config',  function ($resource, config) {

       function transform(response) {

           var insured = response.data.insured;


           return response;
       }

       var memberServicesHostName = config.memberServicesHostName;
       return $resource(memberServicesHostName + '/insureds/:insuredId', null,
       {
           'get': {
               method: 'GET', 'withCredentials': true, interceptor:
               {
                    response: function (response) { return transform(response).data; }
               }
           },
           'update': { method: 'PUT', 'withCredentials': true },
           'save': { method: 'POST', 'withCredentials': true }
       });
   }]);

当我不使用变压器时,“被保险人”在承诺得到解决时处于第一级,它被解析为被保险对象的实例。但是对于转换器,有一个包装器对象,其中包含保险和 responseStatus 属性。这可能与我从拦截器中的“响应”返回的内容有关。一个人应该返回什么,原始响应,就像我正在做的那样,或者 response.data 或 response.resource.insured?我很困惑……

【问题讨论】:

    标签: angularjs angularjs-resource


    【解决方案1】:

    默认的响应拦截器是这样的:

    function defaultResponseInterceptor(response) {
      return response.resource;
    }
    

    因此,如果您想保留默认行为,则必须返回 response.resource 而不是 response.data

    return $resource(memberServicesHostName + '/insureds/:insuredId', null, {
      get: {
        method: 'GET',
        withCredentials: true,
        interceptor: {
          response: function (response) {
            return transform(response).resource;
          }
        }
      },
      ...
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2019-11-12
      • 1970-01-01
      • 1970-01-01
      • 2011-10-06
      • 1970-01-01
      • 2017-10-25
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      相关资源
      最近更新 更多