ionic 2 Error' ReferenceError:未定义sqlitePlugin'

时间:2016-09-17 13:57:20

标签: sqlite angular ionic2 angular-services

我一直在使用离子2 native sqlite plugin制作一个基本应用来捕捉图像并将图像存储到手机本地存储中。当我在genymotion模拟器上运行应用程序时,我不断收到未捕获的异常错误(似乎来自sql插件)。

当我使用-live参数(离线运行android -c -l)重新加载应用程序时,通常会发生这种情况。 我还注意到存储在应用程序中的数据不会出现(这再次表明在实时重新加载时加载存储的数据存在一些问题') 我在下面的控制台上输入了错误:

控制台错误消息

[13:28:27] Starting 'html'...
[13:28:27] Finished 'html' after 42 ms
HTML changed: www/build/pages/home/home.html
HTML changed: www/build/pages/map-detail-component/map-detail-component.html
HTML changed: www/build/pages/map-page/map-page.html
0     298305   log      Angular 2 is running in the development mode. Call enableProdMode() to enable the production mode.
1     298474   group    EXCEPTION: Error: Uncaught (in promise): ReferenceError: sqlitePlugin is not defined
2     298475   error    EXCEPTION: Error: Uncaught (in promise): ReferenceError: sqlitePlugin is not defined
3     298476   error    STACKTRACE:
4     298477   error    Error: Uncaught (in promise): ReferenceError: sqlitePlugin is not defined
    at resolvePromise (http://192.168.56.1:8100/build/js/zone.js:418:31)
    at resolvePromise (http://192.168.56.1:8100/build/js/zone.js:403:17)
    at http://192.168.56.1:8100/build/js/zone.js:451:17
    at ZoneDelegate.invokeTask (http://192.168.56.1:8100/build/js/zone.js:225:37)
    at Object.NgZoneImpl.inner.inner.fork.onInvokeTask (http://192.168.56.1:8100/build/js/app.bundle.js:37360:41)
    at ZoneDelegate.invokeTask (http://192.168.56.1:8100/build/js/zone.js:224:42)
    at Zone.runTask (http://192.168.56.1:8100/build/js/zone.js:125:47)
    at drainMicroTaskQueue (http://192.168.56.1:8100/build/js/zone.js:357:35)
    at XMLHttpRequest.ZoneTask.invoke (http://192.168.56.1:8100/build/js/zone.js:297:25)
5     298478   groupEnd 
6     298481   error    Unhandled Promise rejection:, sqlitePlugin is not defined, ; Zone:, angular, ; Task:, Promise.then, ; Value:, [object Object], ReferenceError: sqlitePlugin is not defined
    at http://192.168.56.1:8100/build/js/app.bundle.js:97420:13
    at new ZoneAwarePromise (http://192.168.56.1:8100/build/js/zone.js:467:29)
    at SQLite.openDatabase (http://192.168.56.1:8100/build/js/app.bundle.js:97419:16)
    at new SqlService (http://192.168.56.1:8100/build/js/app.bundle.js:218:21)
    at DebugAppView.Object.defineProperty.get (MyApp.template.js:18:67)
    at DebugAppView._View_MyApp_Host0.injectorGetInternal (MyApp.template.js:35:79)
    at DebugAppView.AppView.injectorGet (http://192.168.56.1:8100/build/js/app.bundle.js:31753:21)
    at DebugAppView.injectorGet (http://192.168.56.1:8100/build/js/app.bundle.js:31945:49)
    at ElementInjector.get (http://192.168.56.1:8100/build/js/app.bundle.js:31246:33)
    at ElementInjector.get (http://192.168.56.1:8100/build/js/app.bundle.js:31249:48)
7     298519   log      DEVICE READY FIRED AFTER, 1004, ms
8     298609   log      Entering: map-page
9     298620   log      ERROR: , {}

当我重新启动模拟器时会消失,但有时会在更多使用后再次出现。

我认为这可能是因为在导入插件之前创建了SQLite数据库,但是我已经在我的root app.ts文件中导入了该插件(如下所示)(整个应用程序可以在此处看到{ {3}})

root app.ts

@Component({
    template: '<ion-nav [root]="rootPage"></ion-nav>',
    // Declare services
    providers: [ SqlService ]
})
export class MyApp {
    rootPage: any = MapPage;

    constructor(platform: Platform) {
        platform.ready().then(() => {
            StatusBar.styleDefault();
        });
    }
}    
ionicBootstrap(MyApp);

我已将该插件的任何使用限制在sqlService中(如下所示)

SQL服务

import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';
import { SQLite} from 'ionic-native';

@Injectable()
export class SqlService {
  private db: SQLite;
  private isOpen: boolean;

  public constructor() {
    if(!this.isOpen){
      this.db = new SQLite();
      this.db.openDatabase({
        name: "data.db",
        location: "default"
      }).then(() => {
        this.db.executeSql("CREATE TABLE IF NOT EXISTS places (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, img TEXT)", []).then((data) => {
          console.log("TABLE CREATED: " + data);
        }, (error) => {
          console.log("Unable to execute SQL" + error);
        });
        this.isOpen=true;
      });
    }
  }

  public add(title: string, base64Img: string) {
    return new Promise((resolve, reject) => {
      this.db.executeSql("INSERT INTO places (title, img) VALUES ( '"+ title +"', '"+ base64Img +"')", [])
        .then((data) => {
          resolve(data);
        }, (error) => {
          reject(error);
        });
    });
  }

  // Remove individual Location
  public remove(id: number){
    return new Promise((resolve, reject) => {
      this.db.executeSql("DELETE FROM places WHERE id = "+ id +";", [])
        .then((data) => {
          resolve(data);
        }, (error) => {
          reject(error);
        });
    });
  }

  public locDetail(id: number){
    return new Promise((resolve, reject) => {
      this.db.executeSql("SELECT * FROM places WHERE id = "+ id +";",[])
        .then((data) => {
          if(data.rows.length===1){
            // console.log("ttitle: " + data.rows.item(0).title + " id: " + data.rows.item(0).id + " img: " + data.rows.item(0).img );
            let place = [];
            place.push({
              id: data.rows.item(0).id,
              title: data.rows.item(0).title,
              img: data.rows.item(0).img
            });
            resolve(place);
          }
        }, (error) => {
          reject(error);
        });
    });
  }

  // Refresh and initialise the places object
  public refresh() {
    return new Promise((resolve, reject) => {
        this.db.executeSql("SELECT * FROM places", []).then((data) => {
          let place = [];
          if (data.rows.length > 0) {
            for (var i = 0; i < data.rows.length; i++) {
              place.push({ 
                id: data.rows.item(i).id,
                title: data.rows.item(i).title, 
                img: data.rows.item(i).img 
              });
            }
          }
          resolve(place);
        }, (error) => {
          reject(error);
        });
      }
    );
  }
}

3 个答案:

答案 0 :(得分:1)

我最近遇到了同样的问题,请确保您在服务中检查平台是否准备就绪。导入&#34;平台&#34;来自&#34;离子角&#34;并在promise.then方法中执行sqlite交互代码。

答案 1 :(得分:0)

我正在使用IOS并获得相同的错误'ReferenceError: sqlitePlugin is not defined'

由于在Chrome浏览器中测试时sqlite不起作用,我尝试了ionic upload CLI功能。然后得到了同样的错误。

我在Github上遇到this issue

使用setTimeout后,它可以在IOS上的Ionic视图应用中使用:

      setTimeout(function() {
          let db = new SQLite();
            db.openDatabase({
                name: "data.db",
                location: "default"
            }).then(() => {
                db.executeSql("CREATE TABLE IF NOT EXISTS people (id INTEGER PRIMARY KEY AUTOINCREMENT, firstname TEXT, lastname TEXT)", {}).then((data) => {
                    console.log("TABLE CREATED: ", data);
                    self.dummy = data
                }, (error) => {
                    console.error("Unable to execute sql", error);
                    self.dummy = error;
                })
            }, (error) => {
                console.error("Unable to open database", error);
                self.dummy = error;
            });
      }, 2000);  

答案 2 :(得分:-1)

请在模拟器/模拟器或android设备/ ios设备中运行您的项目。它在浏览器上不起作用。