我的服务:服务功能返回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