我是新来的一般使用科尔多瓦和移动开发,但我的代码中有一个非常奇怪的行为。我使用ngCordova的SQLite插件(我使用Ionic),我想要做的事情非常简单:如果存在一个表,那么放弃它或创建它,如果它不存在。我已经为数据库操作创建了一个服务(我不知道是否是最好的方法来做到这一点,但它保持了与控制器分离的那种逻辑)。科尔多瓦的SQLite插件:代码向后运行
的逻辑是这样的:
app.js
angular.module('starter', ['ionic', 'ngCordova', 'starter.controllers', 'starter.services'])
.run(function($ionicPlatform, $ionicLoading, $timeout, initialService) {
$ionicPlatform.ready(function() {
if (!initialService.hasUsers()) { // If there's no table called Usuarios
initialService.createDefaultUser(); // Create table and a record
} else {
$ionicLoading.show({
template: 'Restableciendo...'
});
initialService.resetDatabase(); // Droping table
$timeout(function() {
$ionicLoading.hide();
}, 3000);
}
});
})
services.js
angular.module('starter.services', ['ionic', 'ngCordova']).service('initialService', function($cordovaSQLite, $ionicPopup) {
return {
// Check if Usuarios table exists
hasUsers: function() {
if (ionic.Platform.isAndroid()) {
db = $cordovaSQLite.openDB({
name: "com.pos.db",
iosDatabaseLocation: 'default'
});
} else {
db = $cordovaSQLite.openDB({
name: "com.pos.db",
location: 2,
createFromLocation: 1
});
}
var returnValue;
db.transaction(
function(tx) {
tx.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name='Usuarios'", [], function(tx, result) {
console.log('Existen ' + result.rows.length + ' tablas con el nombre Usuarios');
returnValue = (result.rows.length) ? true : false;
});
}
);
return returnValue;
},
// Creates the Usuarios table and a testing record
createDefaultUser: function() {
var returnValue;
console.log("creando tabla de usuarios");
if (ionic.Platform.isAndroid()) {
db = $cordovaSQLite.openDB({
name: "com.pos.db",
iosDatabaseLocation: 'default'
});
} else {
db = $cordovaSQLite.openDB({
name: "com.pos.db",
location: 2,
createFromLocation: 1
});
}
db.sqlBatch([
'DROP TABLE IF EXISTS Usuarios',
'CREATE TABLE Usuarios (idUsuario INTEGER PRIMARY KEY AUTOINCREMENT, usuario TEXT NOT NULL, tipoUsuario NUMERIC NOT NULL DEFAULT 0, password TEXT)',
"INSERT INTO Usuarios (idUsuario,usuario,tipoUsuario,password) VALUES (1,'mike',0,'123');",
], function() {
returnValue = true;
}, function(error) {
returnValue = false;
});
return returnValue;
},
// Drops the table
resetDatabase: function() {
var returnValue = false;
console.log("Eliminando tabla de usuarios");
db.transaction(
function(tx) {
tx.executeSql("DROP TABLE IF EXISTS Usuarios", [], function(tx, result) {
returnValue = true;
});
}
);
return returnValue;
}
};
});
我与我的手机和Chrome控制台和调试代码的顺序与执行顺序不同:
如何确保所有这些操作都按正确顺序进行?
看看我为这个问题提供的答案:http://stackoverflow.com/questions/39526355/unable-to-create-sqlite-tables-using-javascript-in-for-loop/39528291#39528291 – nyluje
I认为你的问题是相似的,你需要使用'$ .deferred()'来捕获事件完成时的情况。 – nyluje
我在[ngCordova包装](https://github.com/driftyco/ng-cordova/blob/master/src/plugins/sqlite.js)中看到过,它们使用'$ .defer',但我在cordova的插件代码中找不到类似的东西。他们必须做到这一点... – MikeVelazco