2016-04-29 56 views
0

我在控制器中遇到问题,并且承诺。基本上我试图根据我对我的承诺productData收到的回复创建if语句。问题在于承诺内存在变量productData,但在它没有之后 - 变为空。是否因为范围?承诺范围变量

这里是我的代码:

var productData = null; 

ProductService 
    .queryByGroup(selectedGroup.id) 
    .then(function(response) { 
    productData = response.data; 
    }); 

if (productData.hasOwnProperty('conditions') == false) { 
    // Send a request to the server asking for the medicine ids of the selected group 
    Meds 
    .getAllProductsById(selectedGroup.id) 
    .then(function(response) { 

     //SOME CODE logic 

    }, function(response) { 
     $log.debug('Unable to load data'); 
     $log.debug(response.debug); 
    }); 
} else { 
    console.log("call modal"); 
} 

回答

0

你需要处理productData获取响应之后。把你如果条件承诺函数内部

ProductService 
    .queryByGroup(selectedGroup.id) 
    .then(function (response){ 
     productData = response.data; 

     if(productData.hasOwnProperty('conditions') == false){ 
      // Send a request to the server asking for the medicine ids of the selected group 
      Meds 
       .getAllProductsById(selectedGroup.id) 
       .then(function (response) { 

        //SOME CODE logic 

       }, function (response) { 
        $log.debug('Unable to load data'); 
        $log.debug(response.debug); 
       }); 

     }else{ 

      console.log("call modal"); 

     } 
    }); 
1

您的代码的格式不正确,但我的猜测是,你if语句在并行正在执行异步调用$resource。您的承诺尚未解决,因此没有数据驻留在导致错误的productData中。

解决方法是根据promise回调中的productData移动所有内容,以便在解析时将其填充。像这样:

var productData = null; 
ProductService 
    .queryByGroup(selectedGroup.id) 
    .then(function(response) { 
    productData = response.data; 
    if (!productData.conditions) { 
     // Send a request to the server asking for the medicine ids of the selected group 
     Meds 
     .getAllProductsById(selectedGroup.id) 
     .then(function(response) { 

      //SOME CODE logic 

     }, function(response) { 
      $log.debug('Unable to load data'); 
      $log.debug(response.debug); 
     }); 

    } else { 

     console.log("call modal"); 

    } 
    });