1

Hi my code is very simple but i can't get to log the http result to this:

var app = angular.module('app', ['ngRoute']);

app.run(['contacts_helper','$rootScope', function(contacts_helper,$rootScope){
    var x = contacts_helper.getAll();
    console.log(x); // returns undefined 
  }]);

app.service('contacts_helper',['$http','$rootScope', function($http,$rootScope){

  this.getAll = function(){

    $http({
    method:'GET',
    url:'http://localhost/myjson.json',
    params:{id_user:$rootScope.session.id_user}

    }).success(function(response){

     return response;

    }).error(function(err){

     return false;

    });


    }


}]);

it always return undefined in console

So how to achieve this?

2
  • possible duplicate of How to return the response from an AJAX call? Commented Mar 14, 2014 at 15:31
  • 1
    You need to return the promise from the $http call, technically success and error functions haven't run yet by the time x gets assigned, thus x is undefined Commented Mar 14, 2014 at 15:33

1 Answer 1

4

In your interface - you should make getAll is a promise. You need to use .then to access its content:

contacts_helper.getAll().then(function(response){
  console.log(response); 
}]);

This is possible, by changing getAll to return the http call.

this.getAll = function(){

    return $http({
    method:'GET',
    url:'http://facebook.com',
    params:{id_user:$rootScope.session.id_user}

    }).success(function(response){

     return response;

    }).error(function(err){

     return false;

    });

};

Or even simpler:

this.getAll = function(){

    return $http({
    method:'GET',
    url:'http://facebook.com',
    params:{id_user:$rootScope.session.id_user}

    });

};

Also, you should probably read How do I return the response from an asynchronous call?

Sign up to request clarification or add additional context in comments.

2 Comments

hey benji!! it works thanks! thanks i hope you didn't forgot about me :D have nice time mate ;)
@sbaaaang I did not, and frankly I think you should read that 'how to return the response from an AJAX call' post :) Good luck!

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.