javascript ng-cordova s​​qlite 插件:TypeError:无法读取 null 的属性“transaction”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28278503/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 08:42:51  来源:igfitidea点击:

ng-cordova sqlite plugin: TypeError: Cannot read property 'transaction' of null

javascriptangularjssqlitecordovaionic

提问by Chucky

I am trying to get values from database using ionic, ng-cordova, sqlitebut i keep getting this error:

我正在尝试使用 ionic、ng-cordova、sqlite从数据库中获取值,但我不断收到此错误:

TypeError: Cannot read property 'transaction' of null: ionic.bundle.js:19387

Here is the code:

这是代码:

HTML

HTML

<ion-view view-title="Search" ng-controller="AppCtrl2">
  <ion-content>
    <ion-list>
      <ion-item ng-repeat="item in resultados">
        Hello, {{item}}!
      </ion-item>
    </ion-list>
  </ion-content>
</ion-view>

app.js

应用程序.js

var db = null;

angular.module('starter', ['ionic', 'starter.controllers','ngCordova'])

.run(function($ionicPlatform,$cordovaSQLite) {
  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if (window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
    }
    if (window.StatusBar) {
      // org.apache.cordova.statusbar required
      StatusBar.styleDefault();
    }
    db = $cordovaSQLite.openDB({ name: "my.db" });
    $cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS people (id integer primary key, firstname text, lastname text)");
    query = "INSERT INTO people (firstname, lastname) VALUES (?,?)";
    $cordovaSQLite.execute(db, query, ["Sumit", "Pal"]).then(function(res) {
        console.log("INSERT ID -> " + res.insertId);
      });
    $cordovaSQLite.execute(db, query, ["Sumti2", "Pal"]);
  });
})

controller

控制器

.controller('AppCtrl2', function($scope,$ionicPlatform,$cordovaSQLite) {

 $ionicPlatform.ready(function() {

    function getCat() {
      var selectQuery = "SELECT * FROM people";
      $cordovaSQLite.execute(db, selectQuery).then(function(result) {
      nombres = []; 
      for(var i=0; i<result.rows.length; i++){
          nombres.push({"nombre":result.rows.item(0).firstname});
        }
      })
    }
    $scope.resultados =  getCat();       
  })

});

How can i fix it ? The error could be of because device is not yet ready ?

我该如何解决?错误可能是因为设备尚未准备好?

回答by Charles Mendes



Case you do test your app on Browser/Chrome for example, at windows Console (F12) to be error transaction of null, thats ok!!



如果您在浏览器/Chrome 上测试您的应用程序,例如,在 Windows 控制台 (F12) 是 null 的错误事务,那没问题!!

For good test, you would deploy app ionic any device android or ios, or emulated avd.

为了进行良好的测试,您可以在任何设备 android 或 ios 或模拟 avd 上部署应用程序 ionic。

Look my test github example ng-cordova sqlite SELECT and INSERT commands, good luck!

看看我的测试 github 示例 ng-cordova s​​qlite SELECT 和 INSERT 命令,祝你好运!

https://github.com/CharlesMendes/ionic-sqlite
and
https://github.com/CharlesMendes/comandos-basicos

https://github.com/CharlesMendes/ionic-sqlite

https://github.com/CharlesMendes/comandos-basicos

APP.js

应用程序js

$scope.select = function(lastname) {
        var query = "SELECT firstname, lastname FROM people WHERE lastname = ?";
        $cordovaSQLite.execute(db, query, [lastname]).then(function(res) {
            if(res.rows.length > 0) {
                var message = "SELECTED -> " + res.rows.item(0).firstname + " " + res.rows.item(0).lastname;
                alert(message);
                console.log(message);
            } else {
                alert("No results found");
                console.log("No results found");
            }
        }, function (err) {
            alert(err);
            console.error(err);
        });
    }

Deploy do app Android

部署 do app Android

ionic build android

Install apk your device/smartphone android for test

安装 apk 您的设备/智能手机 android 进行测试

adb install -r platforms/android/ant-build/CordovaApp-debug.apk

回答by bocong

You can manually bootstrap the app after the platform is ready Initialize my angularJs App after Phonegap deviceready

您可以在平台准备好后手动引导应用 程序在 Phonegap deviceready 之后初始化我的 angularJs 应用程序

Or you can first navigate to a static loading page, once all the initialization logic is complete in the platform ready method, then navigates to the first functional page

或者您可以先导航到一个静态加载页面,一旦在平台就绪方法中完成所有初始化逻辑,然后导航到第一个功能页面

回答by Kooldandy

Do some changes.

做一些改变。

  1. Remove database connection from app.run(). Put that code in factory service

    dbConnection :function(){
        if (window.cordova) {
            dbconn = $cordovaSQLite.openDB({ name: "my.db" , location: 'default'}); 
            $cordovaSQLite.execute(dbconn, "CREATE TABLE IF NOT EXISTS people (id integer primary key, firstname text, lastname text)");
        }
        else{
            dbconn = window.openDatabase("my.db", '1', 'my', 1024 * 1024 * 100);
            $cordovaSQLite.execute(dbconn, "CREATE TABLE IF NOT EXISTS people (id integer primary key, firstname text, lastname text)");
        }
        return dbconn;
    }
    
  2. Call your getCat()function on device ready.

    document.addEventListener("deviceready", onDeviceReady, false);
    function onDeviceReady() {
       $scope.resultados =  getCat();
    }
    
  1. 从 app.run() 中删除数据库连接。将该代码放入工厂服务中

    dbConnection :function(){
        if (window.cordova) {
            dbconn = $cordovaSQLite.openDB({ name: "my.db" , location: 'default'}); 
            $cordovaSQLite.execute(dbconn, "CREATE TABLE IF NOT EXISTS people (id integer primary key, firstname text, lastname text)");
        }
        else{
            dbconn = window.openDatabase("my.db", '1', 'my', 1024 * 1024 * 100);
            $cordovaSQLite.execute(dbconn, "CREATE TABLE IF NOT EXISTS people (id integer primary key, firstname text, lastname text)");
        }
        return dbconn;
    }
    
  2. getCat()在准备好设备上调用您的函数。

    document.addEventListener("deviceready", onDeviceReady, false);
    function onDeviceReady() {
       $scope.resultados =  getCat();
    }
    

回答by Richard Long

$cordovaSQLite.openDB now requires a compulsory location parameter. Change

$cordovaSQLite.openDB 现在需要一个强制性的位置参数。改变

db = $cordovaSQLite.openDB({ name: "my.db" });

to

db = $cordovaSQLite.openDB({ name: "my.db", location:"default" });

回答by user7069287

I found the solution for this,

我找到了解决方案,

just declare your variable name above the function in index.jsand hence it will load the DB name throughout the controller.

只需在index.js 中的函数上方声明您的变量名称,因此它将在整个控制器中加载数据库名称。

var myDB;
(function() {
    "use strict";

    document.addEventListener('deviceready', onDeviceReady.bind(this), false);

    function onDeviceReady() {

      // Handle the Cordova pause and resume events
      document.addEventListener('pause', onPause.bind(this), false);
      document.addEventListener('resume', onResume.bind(this), false);

      // TODO: Cordova has been loaded. Perform any initialization that requires Cordova here.
      var element = document.getElementById("deviceready");

      myDB = window.sqlitePlugin.openDatabase({
        name: "mySQLite.db",
        location: 'default'
      });
      element.innerHTML = 'Device Ready';
      element.className += ' ready';
    };
});

In Tutorials they have defined myDB within function

在教程中,他们在函数中定义了 myDB