当发布到服务层中的端点以更新用户的配置文件时,我需要从请求有效负载(具有来自客户端的所需修改的配置文件)中删除某些值并将它们重新附加到响应有效负载(更新的配置文件来自服务器)。我目前正在使用 Angular 的请求和响应转换器执行行为,如下所示:
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;
});
我将一个转换器添加到默认请求转换器,并将一个转换器附加到默认响应转换器。我的问题是,有没有更好的方法来做到这一点?也许使用拦截器,如此处所述,而不是?如果是这样,怎么做?