2017-02-25 74 views
-2

我是ionic1框架的新手,並且在sidemenu離子應用上工作。我正在使用cordova local notification其工作正常,但我需要在$ionicPlatform.ready的特定條件下發送通知。對於條件,我使用$http從webservice獲取數據,但不幸的是,我無法從$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); 
})  

我無法從功能$http.get函數中獲取數據。如果我試圖警告它出警報功能undefined

請幫助如何獲取數據。

+0

這已被問及(並回答)至少在單獨的Stackoverflow上千次。 – jcaron

+0

[我如何從異步調用返回響應?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – jcaron

回答

0

這是因爲$ http是一個異步調用,然後當來自http調用的響應可用時調用(), 和您的alert()在來自網絡調用的響應可用之前同步執行。

讀在這裏詳細 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); 

    }); 
}) 

現在您的警報運行時,你從$ HTTP調用的響應。

希望這可以幫助...

+0

謝謝@ mahiraj2709的回覆...我試過異步代碼引用,但沒有運氣,我只是想'$ http.get'函數中的值 – Nupur

+0

爲什麼你不把你的警報放在由promise (函數(響應) {var test = response.data [0]; if(test.result = ='test') { conditionvariable =「false」; } alert(conditionvariable); }); – mahiraj2709

+0

我必須承諾超出承諾的價值,這就是爲什麼我提醒外面 – Nupur