angularjsrestangular

Creating a service around Restangular in AngularJS is not returning array


I am new to AngularJS and Restangular. But being a good citizen I thought I would try to create some services.

While this works and I get an array back populating a drop down list:

Restangular.all('/ta/tas').getList().then(function(tas) {
                $scope.therapyAreas = tas;           
             });

But when I create a service, and then inject the service into the controller I get nothing back:

.controller('prGPTCtrl',['$scope', 'prTAService', 'Restangular', function($scope, prTAService, Restangular) {

            $scope.prGpts = {};
            $scope.therapyAreas = {};


            Restangular.setBaseUrl('resources/pr');         

            $scope.therapyAreas = prTAService.prTAList();

Service:

prServices.factory('prTAService', ['Restangular', '$q', function prTAService(Restangular, $q) {
    return {        
             prTAList : function(therapyAreas) {
                 var therapyAreas = {};
                 Restangular.setBaseUrl('resources/pr');
                 Restangular.all('/ta/tas').getList().then(function(tas) {
                    therapyAreas = tas; 
                    return therapyAreas;
                 }
                );              
             }
    };  
}]);

I see it being called in Chrome Debugger...I suspect it is related to promises (which I don't really "get").

Update:

This works as a service:

prServices.factory('prTAService', ['Restangular', '$q', function prTAService(Restangular, $q) {
    return {        
             prTAList : function(therapyAreas) {                 
                 Restangular.setBaseUrl('resources/pr');
                 return Restangular.all('/ta/tas').getList();
             }
    };  
}]);

And this works when calling it, not sure what I am gaining here!

prTAService.prTAList().then(function(tas) {
                $scope.therapyAreas = tas;
            });

Solution

  • The service needs to return the promise and the controller will handle the return because this is asynchronous. You are doing it right in the last part there:

    prTAService.prTAList().then(function(tas) {
                    $scope.therapyAreas = tas;
                });