我的服務:服務功能返回undefined
var CacheService = angular.module('test.cacheService', []);
CacheService.service('CacheService', function($cordovaSQLite){
var db = null;
this.InitDB = function(){
db = $cordovaSQLite.openDB('my.db', 1);
$cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS settings (key TEXT, value TEXT)");
$cordovaSQLite.execute(db, "INSERT INTO settings (key, value) VALUES(?, ?)" , ['language', 'en']);
};
this.GetCachedLanguage = function(){
$cordovaSQLite.execute(db, 'SELECT * FROM settings WHERE key = "language"').then(function(result){
// OUTPUT DEFINED
alert(result.rows.item(0)['value'] + ' ' + typeof result.rows.item(0)['value']);
return result.rows.item(0)['value'];
});
};
return this;
});
在app.js文件,離子設備上的準備我嘗試使用我的服務:
var app = angular.module('test', ['ionic','ngCordova', 'test.cacheService'])
app.run(function($ionicPlatform, CacheService) {
$ionicPlatform.ready(function() {
if(window.StatusBar) {
StatusBar.styleDefault();
}
CacheService.InitDB();
alert(CacheService.GetCachedLanguage()); //alert show undefined
});
});
所有真實設備測試(IOS)我不明白爲什麼這不起作用,請幫助我,我犯了一個錯誤?
UPDATE:
像@charlietfl說,我需要創建一個回調,對於這個功能,但我不明白,我怎麼能做到這一點
''GetCachedLanguage不返回任何內容和執行'()'是異步也 – charlietfl
@charlietfl是啊,我得到這個,但我怎麼能解決這個問題,我不知道.. – mreoer
使用回調作爲第二個參數。我看到你接受了答案,所以想你已經整理出來了 – charlietfl