Search code examples
arraysangularjsplayframeworkrequestrestangular

RESTAngular: GET request - objects array


I'm trying to make a simple get request for hours, but it just not working. I have a service which responsible of the array , when I defined the array I call service that I built for the restAngular functions.

the first service:

app.factory('ServiceArray',function($filter,restAngularService){

        var Cards = restAngularService.getC();
        console.log(Cards);
return{
            getCards : function(){
                return Cards;
            }
}
//more code...

}

I get undefined from the console.log

the restAngular service :

 app.factory('restAngularService',function($filter,Restangular){
    var Accounts = Restangular.all('api');
    var baseAccounts = Accounts.one('get');
    return{
        getC : function(){
            var Cards = [];
            if(baseAccounts.get()){
                baseAccounts.getList().then(function(b) {
                    console.log(b.plain());
                    Cards = b.plain();
                    return Cards;

                });

            } else {
                return Cards = [{}];
            }
    }
}

from this console.log I get :

[Object, Object]

the controller code :

$scope.Cards = ServiceArray.getCards();
condole.log($scope.Cards);

I get undefined from the console.log


Solution

  • try to return a promise from your getC method like this:

    app.factory('restAngularService',function($filter,Restangular, $q){
        var Accounts = Restangular.all('api');
        var baseAccounts = Accounts.one('get');
    
        var deferred = $q.defer();
    
        return{
            getC : function(){
                var Cards = [];
                if(baseAccounts.get()){
                    baseAccounts.getList().then(function(b) {
                        console.log(b.plain()[0]);
                        Cards = b.plain()[0];
                        deferred.resolve(Cards);
                    });
                } else {
                    deferred.resolve([{}]);
                }
    
               return deferred.promise;
        }
    }
    

    And then you use this service in your controller like this:

    var Cards;
    restAngularService.getC().then(function(cards){
      Cards = cards;
      console.log(Cards);
    });
    

    UPD since your method baseAccounts.getList() is asynchronous it returns promise. So you can't just call it synchronously. So you call it, and add a callback with then. And this callback will be executed when your promise is resolved (eg you get your JSON from the net)