-2

I am new to ionic1 framework and working on sidemenu ionic app. I am using cordova local notification its working fine but i need to send notification on specific condition within $ionicPlatform.ready. For condition, i am getting data from webservice using $http but unfortunately i am unable to retrieve data out of the $http.

 $ionicPlatform.ready(function() {
 var conditionvariable="true";

 $http.get("http://www.example.com/abc.php").then(function(response) 
   {
       var test = response.data[0];
        if(test.result=='test')
                {
                     conditionvariable="false";
                 }   
    });

  alert(conditionvariable);
 })     

I am unable to get data out of the function $http.get function. If i am trying to alert it out of the function it alerts undefined

Please help how to get data.

Nupur
  • 163
  • 2
  • 11
  • This has been asked (and answered) at least a thousand times on Stackoverflow alone. – jcaron Feb 25 '17 at 16:10
  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – jcaron Feb 25 '17 at 16:12

1 Answers1

0

This is because $http is an asynchronous call and then() is called when the response from http call will be available, and your alert() is executed synchronously before the response is available from the network call.

read in detail here Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference

$ionicPlatform.ready(function() {
 var conditionvariable="true";

 $http.get("http://www.example.com/abc.php").then(function(response) 
   {
       var test = response.data[0];
        if(test.result=='test')
                {
                     conditionvariable="false";
                 }  
    alert(conditionvariable);

    });
})

now your alert runs when you get the response from the $http call.

hope this helps...

Community
  • 1
  • 1
  • thank you @mahiraj2709 for the reply...I have tried Asynchronous code reference but no luck i just want value out of the `$http.get` function – Nupur Feb 27 '17 at 08:47
  • why don't you put your alert inside the then returned by the promise..$http.get("http://www.example.com/abc.php").then(function(response) { var test = response.data[0]; if(test.result=='test') { conditionvariable="false"; } alert(conditionvariable); }); – mahiraj2709 Feb 27 '17 at 13:46
  • I have to take value outside the promise that's why i alert this outside – Nupur Feb 28 '17 at 05:15