Javascript 正确使用变压器与拦截器
当发布到服务层中的端点以更新用户的配置文件时,我需要从请求有效负载(具有来自客户端的所需修改的配置文件)中删除某些值,并将它们重新附加到响应有效负载(来自服务器的更新配置文件)中。我目前正在使用Angular's执行行为,如下所示:Javascript 正确使用变压器与拦截器,javascript,angularjs,angular-http,angular-http-interceptors,Javascript,Angularjs,Angular Http,Angular Http Interceptors,当发布到服务层中的端点以更新用户的配置文件时,我需要从请求有效负载(具有来自客户端的所需修改的配置文件)中删除某些值,并将它们重新附加到响应有效负载(来自服务器的更新配置文件)中。我目前正在使用Angular's执行行为,如下所示: myService.updateProfile = function (profile) { return $http({ method: 'POST', withCredentials: true, url
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;
});
我在默认的请求转换器前面加了一个转换器,并在默认的响应转换器后面加了一个转换器。我的问题是,有没有更好的办法?也许用它来代替?如果是,怎么做?我认为您的解决方案很好,但如果您需要其他解决方案,您可以拦截类似这样的特定请求。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');
我只是将http请求包装到服务中。基本上,在调用之前,您将其剥离,然后将其还原,您可以将其添加回.then调用中。您可以使用拦截器,但它们对于全局拦截HTTP请求/响应(意味着每次调用)非常有用。您仍然可以使用拦截器,但必须确定只由拦截器处理的特定API路由。