2016-12-19 2 views
0

각도로 $ q.when를 사용하여 백엔드 API에서 값을 내 컨트롤러로 가져 오려고합니다. 내 컨트롤러의 함수가 $ http 서비스로 백엔드를 호출하는 다른 함수를 호출하는 서비스에서 비동기 함수를 호출하고 있습니다.

$ q.when이 응답 개체를 성공적으로 기록하지만 개체의 속성을 기록하려고하면 빈 채로 표시됩니다. 이것으로 무엇을해야합니까? 응답 값이 되돌아 오기 전에 값이 할당 된 것 같아요.하지만 $ q의 .then 문은이 일을 처리해야한다고 생각 했나요?

컨트롤러 :

init(); 

function init(){ 

    $q.when(MyProfileService.fetchProfile()).then(function(response){ 

    // This logs the object and I can see the email property is populated: 
    console.log("resolved with value:"); 
    console.log(response); 

    // This comes up with blank value 
    console.log("attempting to log response data:") 
    console.log(response.user.email); 

    }); 
} 

MyProfileService :

function fetchProfile() { 
    return ProfileService.getProfile() 
    .then(function(response){ 

    var profileObject = ProfileSaveService.getData(); 

    var transRef = { transientRef: profileObject.card.transientRef } 

    // and pass it into the function for retrieving the estatement optin details. 
    fetchEstatementStatus(transRef); 

    return service; 
    }).catch(function(error){ 
     console.error(error); 
    }); 
} 

function fetchEstatementStatus(transRef) { 

    return HttpService.httpPost('/dash/v1/account/retrieveCommProfile', transRef) 
    .then(function(response) { 

     service.user.email = response.data.userEmail; 

     // This should return the service object with all the properties set: 
     return service; 
    }) 
    .catch(function(error) { 
     return $q.reject(error); 
    }); 

} 
+1

는'ProfileSaveService.getData()'비동기 호출인가? 그렇다면 transientRef가 제대로 채워지지 않습니다. 마찬가지로'transientRef'라는 변수를 선언했는데'fetchEstatementStatus' 변수에'transRef'라는 변수를 넘겨 줬습니다, 그냥 오타였습니까? –

+0

ProfileSaveService.getData가 비동기 호출이 아닙니다. transientRef가 올바르게 채워집니다. 그것은 읽어야합니다 : var transRef = {transientRef : profileObject.card.transientRef} – JamesNB

+0

그것은 모든 문제를 제외하고 제대로 응답을 기록하지만 response.user.email을 지적했습니다. response.user.email이 비어 있습니다. – JamesNB

답변

0

당신은 비동기 fetchEstatementStatus(transRef); 호출을 발사하지만 대기하지 않습니다. 대신 즉시 service을 반환합니다. 당신은 then 콜백에서 약속을 return 할 필요가 대기로 만들려면 :

function fetchProfile() { 
    return ProfileService.getProfile().then(function(response){ 
     var profileObject = ProfileSaveService.getData(); 
     return fetchEstatementStatus({transientRef: profileObject.card.transientRef}); 
//  ^^^^^^ 
    }).catch(function(error){ 
     console.error(error); 
    }); 
} 

function fetchEstatementStatus(transRef) { 
    return HttpService.httpPost('/dash/v1/account/retrieveCommProfile', transRef).then(function(response) { 
     service.user.email = response.data.userEmail; 
     return service; 
    }); 
} 
+0

고맙습니다. 반드시 깨어있는 월요일이 아니어야합니다. 당신은 보석입니다. – JamesNB