4
사용자 프로필을 업데이트하기 위해 서비스 레이어의 끝점에 게시 할 때 요청 페이로드 (클라이언트에서 원하는 수정 사항이있는 프로필)에서 특정 값을 제거하고 다시 첨부해야합니다 응답 페이로드 (서버의 업데이트 된 프로파일)에 있습니다. 나는 현재이 같은 각도의 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 요청을 그냥 래핑합니다. 기본적으로 호출하기 전에 스트립 한 다음 다시 내려옵니다. 다시 호출 할 수 있습니다. – Strawberry
인터셉터를 사용할 수 있지만 대부분은 (요청할 때마다) HTTP 요청/응답을 가로 채는 데 유용합니다. 여전히 인터셉터를 사용할 수 있지만 인터셉터에서만 처리 할 특정 API 경로를 결정해야합니다. –