0

Hi Everyone I'm sure there is a simple solution to this problem but I can't seem to find it myself...

I have a controller that assigns data to the $scope.items variable by calling a service defined as GetDataService

$scope.items = GetDataService.getData('/getBroadcastSourceList/1');

The service is set up as follows:

angular.module('appName')
  .service('GetDataService', function($http, WebServiceURL) {
    this.getData = function(ServiceParameter) {
      $http.get(WebServiceURL + ServiceParameter)
        .then(function(res){
          return res.data;
        });
    };
  });

I have stepped through my code in the GetDataService and can see that res.data does contain all relevant data however this data is not sent to $scope.items in my controller.

I have also checked that all is well on my controller side by changing my service as follows:

angular.module('appName')
      .service('GetDataService', function($http, WebServiceURL) {
        this.getData = function(ServiceParameter) {
           return [{
                     Day: "Monday",
                     Language: "English "
                   }]
        };
      });

This does populate $scope.items so the issue must be somewhere here:

$http.get(WebServiceURL + ServiceParameter)
        .then(function(res){
          return res.data;
        });

What am I doing wrong?

2 Answers 2

4

$http service is aync in nature so you need to assign data in a callback

GetDataService.getData('/getBroadcastSourceList/1').then(function(data) {
  $scope.items=data;
})

Also your service does not have a return, add it.

this.getData = function(ServiceParameter) {
      return $http.get(WebServiceURL + ServiceParameter)
Sign up to request clarification or add additional context in comments.

4 Comments

OP not returning $http to do that
Thanks for this it works except the object that gets returned consists of .config, .data and .headers. How do I only return the data part and not the other stuff?
But right now $scope.items = data.data; gets me what I want
If you keep the then in place, you would not have to do data.data
0

You are not retuning nothing on the getData method of your service try to return a promise

angular.module('appName')
  .service('GetDataService', function($http, $q WebServiceURL) {
    this.getData = function(ServiceParameter) {
var defer = $q.defer();
      $http.get(WebServiceURL + ServiceParameter)
        .then(function(res){
         defer.resolve(res.data);
        }, function (err) { defer.reject(err)});
return defer.promise;
    };

1 Comment

yep you can return the promise from $http anyway

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.