【问题标题】:Proper use of transformers vs interceptors正确使用变压器与拦截器
【发布时间】:2014-12-10 20:15:35
【问题描述】:

当发布到服务层中的端点以更新用户的配置文件时,我需要从请求有效负载(具有来自客户端的所需修改的配置文件)中剥离某些值并将它们重新附加到响应有效负载(从服务器更新的配置文件)。我目前正在使用 Angular 的 request and response transformers 执行行为,如下所示:

myService.updateProfile = function (profile) {

    return $http({
        method: 'POST',
        withCredentials: true,
        url: root + 'users/profile',
        data: profile,
        transformRequest : requestTransformer,
        transformResponse : responseTransformer
    });

};

// the map used during transformation below
var myMap = {
    0: 'foo', 
    1: 'bar',
    2: 'etc'
};

// prependTransform() and appendTransform() are similar to the example provided in Angular transformer docs here:
// https://docs.angularjs.org/api/ng/service/$http#overriding-the-default-transformations-per-request
var requestTransformer = httpTransformer.prependTransform($http.defaults.transformRequest, function(profileRequest) {
    profileRequest.myKey = myMap.indexOf(profileRequest.myValue);
    delete profileRequest.myValue;

    return profileRequest;
});
var responseTransformer = httpTransformer.appendTransform($http.defaults.transformResponse, function(profileResponse) {
    profileRequest.myValue = myMap[profileRequest.myKey];
    delete profileRequest.myKey;

    return profileResponse;
});

我在默认请求转换器前添加一个转换器,并将一个转换器附加到默认响应转换器。我的问题是,有没有更好的方法来做到这一点?也许改用interceptors, as documented here,?如果有,怎么做?

【问题讨论】:

  • 我只是将 http 请求包装在一个服务中。基本上,在调用之前,你先剥离它,然后它又回来,你可以在 .then 调用中添加它。
  • 您可以使用拦截器,但它们最有助于在全局范围内拦截 HTTP 请求/响应(意味着每次调用)。您仍然可以使用拦截器,但您必须确定仅由您的拦截器处理的特定 API 路由。

标签: javascript angularjs angular-http angular-http-interceptors


【解决方案1】:

我认为你的解决方案很好,但如果你想要一个替代方案,你可以像这样拦截特定的请求。 HTTP 拦截器主要用于处理全局 HTTP 请求/响应(身份验证、错误处理等)。

在任何情况下,都应该从 API/服务器端处理“响应”负载。

$provide.factory('userProfileInterceptor', function() {
  return {
    request: function(config) {
       if (config.url.indexOf('/users/profile') >=0){
           if (config.params.myValue) delete config.params.myValue;
       }
       return config;
    },
    response: function(response) {
       if (response.config.url.indexOf('/users/profile') >=0){
           delete response.data.myKey;
       }
       return response;
    }
  };
});

$httpProvider.interceptors.push('userProfileInterceptor');

【讨论】:

    猜你喜欢
    • 2014-03-10
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 2022-01-17
    • 2021-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多