承诺范围变量

时间:2016-04-29 16:58:57

标签: angularjs angularjs-scope

我的控制器中有一个承诺存在问题。基本上我正在尝试根据我对productData的承诺收到的响应创建一个if语句。问题是变量productData存在于promise中,但在它没有之后 - 它变为null。是因为范围?

这是我的代码:

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

2 个答案:

答案 0 :(得分: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");

    }
  });

答案 1 :(得分:0)

获得回复后,您需要处理 productData 。将你的if条件放在promise函数中

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

        }
    });
相关问题