3

I'm trying to set a variable as the data object returned from a http request in angular, but the variable never sets to even if it is in the $scope unless it is nested within the success function. For example, if I do this in the controller :

    $scope.hello = [];
       var getAppointmentsurl = './dbscripts/getAppointments.php';

          $http({method: 'GET', url: getAppointmentsurl}).success(function(data) {

                $scope.hello = data;
          });

          console.log($scope.hello);

}

Hello is blank... so I set it up in services.js like this :

 this.getCalendarData=function(){
        var hello = [];
           var getAppointmentsurl = './dbscripts/getAppointments.php';

              $http({method: 'GET', url: getAppointmentsurl}).success(function(data) {

                    hello = data;
              });

              return hello;

    }

but still hello is blank. Am I missing something obvious?

edit -- enter image description here

Gaz Smith
  • 1,100
  • 1
  • 16
  • 30
  • try to put the console.log or the return inside the function and you ll see the your results – Vanojx1 Aug 02 '16 at 13:50
  • All the data is in 'data', thats coming through fine – G.Smith Aug 02 '16 at 13:50
  • Check [this](http://stackoverflow.com/questions/12505760/processing-http-response-in-service). $http is async and you should apply different methodology to get result of it. – Tuğca Eker Aug 02 '16 at 13:52

3 Answers3

3
 this.getCalendarData=function(){
       var getAppointmentsurl = './dbscripts/getAppointments.php';

          return $http({method: 'GET', url: getAppointmentsurl}).success(function(data) {

                return data;
          });


}

This is asynchronus call we have to return data like above.

0

As you put the api call as a method in the service, returning data from the service wont resolve yet, So in the controller the service return will only be a promise

serviceName.getCalendarData().then(function(data){

   //Success data
},function(){});

Service code must return like the below code and here you will get the entire response object,

return $http({method: 'GET', url:getAppointmentsurl});

One other way to get the data directly resolved stripping of the other properties is returning from service like this,

return $http({method: 'GET', url:getAppointmentsurl}).success(function(data){

    return data;
});
Shintu Joseph
  • 962
  • 7
  • 19
0

To elaborate on Akash's correct answer, here's an example of how it should work.

In your view you should add logic to show the data only when hello exists. i.e. ng-if="hello"

controller:

ServiceName.getCalendarData().then(function(response) {
  $scope.hello = response;
});

service:

this.getCalendarData = function() {
  return $http.get('path/to/response/').success(function(data) {
    return data;
  });
}
zilj
  • 619
  • 1
  • 7
  • 13