2016-10-19 3 views
0

간결하고 모듈화 된 코드를 유지하려면 다음 HTTP 호출 처리 방법을 사용하고 있습니다. 컨트롤러에서

내가 할 :

서비스에서
function makeCall(){ 
    Service.getDetails(url, obj).then(responseFn, errorFn); 
} 

내가 할 :

this.getDetails = function(url, obj){ 
return $http.get(url); 
} 

그런 다음 컨트롤러에서 내가 가진 :

function responseFn(){ 
    //response objct available here by deafult 
} 

function errorFn(){ 
//error objct available here by deafult 

} 

이 함수에서 내가 자동 응답 및 오류 목적. 하나의 경우에는 GET의 응답 만 필요하므로 괜찮습니다.하지만 다른 컨트롤러에서 동일한 메서드를 호출하는 또 다른 경우에는 응답을 조작하기 위해 조건을 사용해야합니다.

쿼리 : 원래의 makeCall 함수에서이 콜백 함수에 'obj'매개 변수를 전달하려면 어떻게해야합니까? 콜백 함수에 두 개의 더미 변수를 전달하면 작동하지 않습니다. (첫 번째 인수가 응답으로 대체되고 두 번째 인수가 내 인수로 바뀔 것으로 예상 됨)

답변

0

옵션 중 하나는 반환하는 개체를 확장하는 것입니다.이 경우 컨트롤러를 통해 데이터에 액세스 할 수 있습니다. 서비스에

:

this.getDetails = function(url, obj){ 
    this.myObjData = obj; // bind it to your returing object 
    return $http.get(url); 
} 

컨트롤러에서 :

function makeCall(){ 
    Service.getDetails(url, obj).then(responseFn, errorFn); // respond parameter will attach by default, no need to bind it here 
} 

function responseFn(respond){ 
    console.log(respond); // will attach by default 
    console.log(Service.myObjData); // access your data from here 
} 

는 당신을 도울 바랍니다.

관련 문제