Access variable from within the scope of the promise

0

I have a factory that must access two other services. Being the following structure:

angular.module('my.module')
.factory('ServiceMain', ServiceMain);

ServiceMain.$inject = ['ServicePrimary', 'ServiceSecondary'];

function ServiceMain(ServicePrimary, ServiceSecondary){

  var service = {
       execute: execute
  }

  return service;

  function execute(){

    ServicePrimary.getData().then(function(result){

      var arrayData = [];

      var indiceForSync = 0;
      for(var indice = 0; indice < result.length; indice++ ){

        if(result[indice].valor <= 0){
            continue;
        }

        arrayData[indiceForSync] = {
            clientes: result[indice],
          pacotes: []
        }

        indiceForSync++;
      }

      if(arrayData.length) {

            for (var indiceData = 0; indiceData < arrayData.length; indiceData++) {

              ServiceSecondary.getPackages(arrayData[indiceData].valor).then(function(packs){
                //Aqui nao eh possivel enxergar o arrayData...
                for(var indicePacks = 0; indicePacks < packs.length; indicePacks++ ){
                  //a ideia era chamar o array data para preencher o array pacotes
                  arrayData[indiceData].pacotes[indicePacks] = packs[indicePacks];
                }
              });

          }//end for

      }
    });
  }
}

Within the call of the second service (ServiceSecondary), within the promise I do not have access to the variable arrayData. I've tried invoking this (something like: var vm = this; ) and then declaring it with vm.arrayData , and in the last act, I tried to use $ rootScope, but nothing works.

Is there a way to access this variable within the scope of the promise? or will the implementation be in trouble?

    
asked by anonymous 04.04.2017 / 15:41

1 answer

1

A variable referring to this (as var vm = this ) should work yes, but be sure to initialize it in the scope of ServiceMain , not execute . I also advise using Angle ( angular.forEach ) to make interactions with objects.

    
07.04.2017 / 16:27