Search code examples
javascriptarraysangularjsajaxangular-resource

Empty array after get request (AngularJS)


In my example when I send a GET request to get a response array with data, then I see in the console of firefox the array is empty. I don't know where the error is. enter image description here

Here is my code:

//Controller:
$scope.changeDate = function (selFrom) {
     vm.repos = CrudService.getRepoByDay(selFrom);
}


//Service (CrudService):
function CrudService(ResService) {
    var service = {
        getRepoByDay: getRepoByDay
    };

    return service;

    function getRepoByDay(selTo) {
      return ResourceService.test.query(
         { endDate: selTo },
         successResponse,
         errorResponse
      );
    }

    function successResponse(response) {
       return response;
    }
}

//Service (ResService)
test: $resource(baseUrl + '/api/repodates', {
         endDate: '@EndDate'
}, {})

//View
<tbody>
  <tr ng-repeat="report in rc.repos>
    <td ng-repeat="(key, value) in report">
        {{ value }}
    </td>
  </tr>
</tbody>

Do anyone have an idea what I have to do?


Solution

  • $resource is asynchronous you have to handle it in the callback of the promise :

    return ResourceService.test.query(
         { endDate: selTo } 
    );
    
    CrudService.getRepoByDay(selFrom).$promise.then(function(data){
           vm.repos = data;
           console.log(data);//log here not ouside the callback to check
    });
    

    EDIT sample with $q :

    var deferred = $q.defer();
    ResourceService.test.query(
        { endDate: selTo } 
    ).$promise.then(
         function(data){deferred.resolve(data);},
         function(rejection){deferred.reject(rejection);}
    );
    return deferred.promise;