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,을 대신 사용 하시겠습니까? 그렇다면 어떻게?

+0

서비스에서 http 요청을 그냥 래핑합니다. 기본적으로 호출하기 전에 스트립 한 다음 다시 내려옵니다. 다시 호출 할 수 있습니다. – Strawberry

+0

인터셉터를 사용할 수 있지만 대부분은 (요청할 때마다) HTTP 요청/응답을 가로 채는 데 유용합니다. 여전히 인터셉터를 사용할 수 있지만 인터셉터에서만 처리 할 특정 API 경로를 결정해야합니다. –

답변

0

나는 해결책이 좋다고 생각하지만 대안을 원할 경우 그렇게 특정 요청을 차단할 수 있습니다. 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');