【发布时间】: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