2

My Code is:

$rootScope.getResource = function(id) {
  $http.get( "path/of/resource/" + id )
    .success(function (data, status, header, config) {
    return data;
  })
    .error(function (data, status, header, config) {
    console.log("Error");
  });

But it always returns 'undefined'.

I know the problem is the $http function is asynchronous and I should use promises, but I can't figure out how to do everything inside just a function in $rootScope.

Muhammad Reda
  • 26,379
  • 14
  • 93
  • 105
Francesco Borzi
  • 56,083
  • 47
  • 179
  • 252
  • can you plz elaborate your problem – shreyansh Jun 07 '15 at 11:50
  • 3
    Return the promise: `return $http.get( "path/of/resource/" + id );`. Read http://blog.ninja-squad.com/2015/05/28/angularjs-promises/ – JB Nizet Jun 07 '15 at 11:50
  • 1
    why are you attaching getResource to $rootScope? You should use a factory. – Donal Jun 07 '15 at 12:17
  • possible duplicate of [How to return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Quentin Jun 07 '15 at 15:58

1 Answers1

0

You should return the data withing a callback.

$rootScope.getResource = function(id, callback) {

  var cb = callback || angular.noop;

  $http.get( "path/of/resource/" + id )
    .success(function (data, status, header, config) {
    return cb(data);
  })
    .error(function (data, status, header, config) {
    console.log("Error");
    return cb('error');
  });

Then, to make use of the updated getResource function

$scope.assignReturnedData = $rootScope.getResource(15, function(data) {
    $scope.yourVariable = data;
});

You can get the idea from this working plunker.

One side note, I wouldn't encourage you using $rootScope to get data, instead you should look into using angular service.

Muhammad Reda
  • 26,379
  • 14
  • 93
  • 105
  • 3
    This is an anti-pattern. The OP should instead return the promise. That would allow the caller to do whatever it wants in case of success, and whatever it wants in case of error. `return $http.get( "path/of/resource/" + id )` is all you need. If you really want to log in case of error, then use `return $http.get( "path/of/resource/" + id ).catch(function(r) { console.log('error'); return $q.reject(r); });` – JB Nizet Jun 07 '15 at 13:35