1

I need to get value from http.get function but I don't know how. Please help.

here is my code

$http.get(base_url+"user/feach_one")
   .then(function (response) {$scope.my = response.data;

     $scope.email=$scope.my.email;
     console.log("email from get:"+$scope.email);

});

console.log("Get email from outside:"+$scope.email);

This is the result in console:

Get email from outside:undefined
myangular.js:90 email from get:myemail@yahoo.com
Ramesh Rajendran
  • 37,412
  • 45
  • 153
  • 234
Vuong Tran
  • 466
  • 1
  • 4
  • 12
  • 3
    You are doing it right, you will be able to get the value from outside the ".then" but only once it is resolved. What are you trying to do ? The console.log outside is called before the request is resolved but the value is set in your scope object – Groben May 19 '17 at 09:07
  • Make sure url is correct - Debug it - see browser console error type – Asif Raza May 19 '17 at 10:11

2 Answers2

1

$http is an asynchronous call so this line:

console.log("Get email from outside:"+$scope.email);

Can be executed before $http.get( ...). You should put in in the .then statement of the $http call:

$http.get(base_url+"user/feach_one").then(function (response) {
    $scope.my = response.data;
    $scope.email=$scope.my.email;
    console.log("email from get:"+$scope.email);
    console.log("Get email from outside:"+$scope.email);
});
Mistalis
  • 17,793
  • 13
  • 73
  • 97
0

Your code doesn't work because inside the $http.then function, $scope does not refer to the same $scope you're trying to access from outside the function. In order to make it work, you either need to put your response.data on the $parent scope, like so:

.then(function (response) {$scope.$parent.my = response.data;...}

Or you can return a value from within your .then function and assign that to your $scope within the controller (assuming you're using a service for the $http request).

function makeHttpReq(okcallback, errorCallback) {

    $http.get(base_url+"user/feach_one")
      .then(function (response) {
        okCallback(response.data)
    });

And then you can call the function in your controller like so:

makeHttpReq(function (data) {
    $scope.my = data;
}
bamtheboozle
  • 5,847
  • 2
  • 17
  • 31