当我得到一个值时,从一个有角度的$ q延迟调用中获取一个状态对象

时间:2016-12-19 17:24:28

标签: angularjs angular-promise

我正在尝试使用$ q.when在angular中从后端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 个答案:

答案 0 :(得分:0)

您启动了异步fetchEstatementStatus(transRef);调用,但从不等待它。相反,您立即返回service。您需要return来自then回调的承诺才能让它等待:

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;
    });
}