How to create a function that returns a value fetched with $http

75 views Asked by At

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.

1

There are 1 answers

1
Muhammad Reda On

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.