Access variable from within the scope of Promise

Asked

Viewed 377 times

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 Omise I do not have access to the variable arrayData. I’ve tried calling this (something like: var vm = this; ) and then declare it with vm.arrayData, and last act, I tried to use $rootScope, but nothing works.

Is there a way to access this variable within the scope of Promise? or is the implementation having problems?

1 answer

1

A variable referring to the this (as var vm = this) should work yes, but remember to initialize it in the scope of ServiceMain, not in function execute. I also recommend using the loop of Angular (angular.forEach) to make interactions with objects.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.