0

I have created angularJs factory service to dealing with REST calls.Service is worked fine.I have some cases that i need to set values in to $scope.variable and access them in outside of resource service.But i got undefined. I wrapped them inside angularJs $q but seems like i did some mistake.please help me to solve this.

AngularJs Factory

myApp.factory('MyService',function($resource) {

    return{
       GetMYData:$resource(my rest service URL, {});
      }

    });

In Controller

$scope.myMap={};
$scope.promises=[];
$scope.myData = MyService.GetMYData.query();
            $scope.myData.$promise.then(function (result) {

            result.forEach(function(e, i) {
             //Do something
              var deferred = $q.defer();
              $scope.myMap[e.key]=e; //Put elements into map and i tried to access map from outside service by giving key

              deferred.resolve(result);
              $scope.promises.push(deferred.promise);
              $scope.myMap[$location.search()['dataID']] //This display the actual value
            })
    ...
}

If URL parameter present in the URL i do the following things.

if($location.search()['dataID']){

   $q.all($scope.promises).then(
   function(data) {
          console.log($scope.myMap[$location.search()['dataID']]) // throws      undefined
    },function(response) {
         //Handle if promises are rejected
        })
}

Please let me know how can i access the map values set by angularJs resource service from outside of service.

gihan-maduranga
  • 4,381
  • 5
  • 41
  • 74

1 Answers1

0

What I'll try to do is:

     myApp.factory('MyService',function($resource) {




 var _resource = $resource(my rest service URL, {},{
             query:{method:"GET",IsArray:true}
       })


            return{
               GetMYData:function(){
                       return _resource.query();
                      }
              }

            });

then:

$scope.myMap={};
$scope.promises=[];
 MyService.GetMYData.$promise.then(function (result) {

            result.forEach(function(e, i) {
             //Do something

              $scope.myMap[e.key]=e; //Put elements into map and i tried to access map from outside service by giving key



              $scope.myMap[$location.search()['dataID']] //This display the actual value
            })
    ...
}

and then access simply your

if($location.search()['dataID']){

  console.log($scope.myMap[$location.search()['dataID']]) );

}
federico scamuzzi
  • 3,708
  • 1
  • 17
  • 24
  • i tried this but map is empty when accessing outside of the service thats why i used promises to wait until resolved. – gihan-maduranga Feb 01 '17 at 08:16
  • sorry but are you using the service just only to retirve data..the you put the data in the $scope.myMap in the same controller wher you access it? – federico scamuzzi Feb 01 '17 at 08:20