Can't get the right thing to return


#1

My controller code:

.controller('DashCtrl', function($scope, Files) {
    $scope.getFiles = function() {
      Files.test().then(function(results) {
        $scope.files = results;
      });
    };
})

My factory code:

app.factory('Files', function($http) {
  return {
    test: function() {
      var call = 'https://www.somesite.com';
      $http({method: 'GET', url: call}).
        success(function(data) {
          // Do some stuff to data..
          // blah blah blah
          return results;
        }).
        error(function(data, status, headers, config) {
          return;
        });
    }
  }
});

That code throws the error:

“Cannot read property ‘then’ of undefined”

If I change the $http line to:

return $http({method: 'GET', url: call}).

Then the “data” variable gets returned and not the “results” variable.

What am I doing wrong?


So, here is how I resolved it:

.controller('DashCtrl', function($scope, Files) {
    $scope.getFiles = function() {
      Files.test().then(function(results) {
              // Do some stuff to data..
              $results = data blah blah
              // blah blah blah
          $scope.files = $results;
      });
    };
})

Factory code:

app.factory('Files', function($http) {
  return {
    test: function() {
      var call = 'https://www.somesite.com';
      return $http({method: 'GET', url: call}).
        success(function(data) {
        }).
        error(function(data, status, headers, config) {
        });
    }
  }
});

Thanks!


#2

Is the GET request throwing an error? If so, your code is returning nothing in the error handle. .then() calls either the success callback or the error callback.

Can you try returning data and logging it to the console in both handles?


#3

The get is working fine. I can see the data in console.log().

The problem is that when I do return with $http it returns the raw “data” variable and not the “results” variable.


#4

I moved the data processing stuff into the controller and left the getting in the service file and this seems to work.

The only problem now is that Angular is interpreting each letter of the array instead of each item of the array. Strange.


#5

Ahh I see - I thought you were returning the http request object. So if you want to return data from success callback you’ll need to return a promise - your factory function would look like:

myFactoryFunction: function(){
    var deff = $q.defer();
    // Now we can make the async request to return the data
    $http.get('http://time.jsontest.com')
        .success(function(data){
            deff.resolve(data);
        ])
        .error(function(data){
           deff.reject(data);
        });
     // Return the promise
     return deff.promise
}

From there you can call MyFactoryFunction().then(data){...} - just remember to inject the $q module to your factory.


#6

I don’t have anything in .success and it’s returning into the “then” just fine.