javascript - 正确使用变压器与拦截器

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

当 POST 到服务层中的端点以更新用户的配置文件时,我需要从请求有效负载(具有来自客户端的所需修改的配置文件)中剥离某些值,并将它们重新附加到响应有效负载中(从服务器更新配置文件)。我目前正在使用 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 拦截器主要用于处理全局 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');

关于javascript - 正确使用变压器与拦截器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26387868/

相关文章:

javascript - ReactJS:Express API 和 ReactJS 结构限制每行显示数据

javascript - Jasmine /Angular Testing 语法混淆

javascript - 禁用iframe src的监听

javascript - 在 Angularjs 中,你如何改变每个测试的模拟服务?

angular - http.get 太慢,更改检测未注册更改

javascript - 无法更改数据表标题

javascript - 如何获取数据迭代Json?

angularjs - 一旦兑现 promise ,就更新 ng-include 模板内的变量

javascript - JQuery 响应式菜单不起作用

cookies - angular2,带有凭据的http。无法添加 cookie