vlntn
vlntn

Reputation: 370

How to fix 'TypeError: Cannot read property 'then' of undefined TypeError: Cannot read property 'then' of undefined...'

Im about to build a Ionic Inventory Management app with Barcode Scanner and SQLite with the help of this tutorial: https://www.techiediaries.com/ionic-cordova-sqlite-barcode-scanner-product-inventory-manager/

When I add this code:

 constructor(public sqlite :SQLite) {
          console.log('Hello DataServiceProvider Provider')

              this.sqlite.create({name: "data.db", location: 
    "default"}).then((db : SQLiteObject) => {
                      this.database = db;
                  }, (error) => {
                      console.log("ERROR: ", error);
              }); 

...to data-service.service.ts I got this error:

core.js:19866 ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'then' of undefined TypeError: Cannot read property 'then' of undefined at new DataServiceService (data-service.service.ts:64) at _createClass (core.js:26976) at createProviderInstance (core.js:26941) at resolveNgModuleDep (core.js:26888) at NgModuleRef.get (core.js:27996) at resolveNgModuleDep (core.js:26908) at NgModuleRef_.get (core.js:27996) at resolveDep (core.js:28518) at createClass (core.js:28366) at createDirectiveInstance (core.js:28186) at resolvePromise (zone.js:831) at resolvePromise (zone.js:788) at zone.js:892 at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423) at Object.onInvokeTask (core.js:21826) at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:422) at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:195) at drainMicroTaskQueue (zone.js:601)

This is the whole data-service.service.ts code:

import { Injectable } from '@angular/core';

import { SQLite, SQLiteObject } from '@ionic-native/sqlite/ngx';



@Injectable({
  providedIn: 'root'
})
export class DataServiceService {
  public database: SQLiteObject;

  productTable : string = `CREATE TABLE IF NOT EXISTS  products (
    id INTEGER PRIMARY KEY,
    sku TEXT,
    barcode TEXT,
    title TEXT NOT NULL,
    description TEXT,
    quantity REAL,
    unit VARCHAR,
    unitPrice REAL,
    minQuantity INTEGER,
    familly_id INTEGER,
    location_id INTEGER,
    FOREIGN KEY(familly_id) REFERENCES famillies(id),
    FOREIGN KEY(location_id) REFERENCES locations(id)
    );`;

familyTable : string = `CREATE TABLE IF NOT EXISTS famillies (
    id INTEGER PRIMARY KEY,
    reference VARCHAR(32) NOT NULL,
    name TEXT NOT NULL,
    unit VARCHAR);`;

locationTable : string = `CREATE TABLE IF NOT EXISTS locations (
        id INTEGER PRIMARY KEY,
        name TEXT NOT NULL);`;
//Date , Quantity , Unit Cost , Reason (New Stock - Usable Return - Unusable Return ) ,UPC (Universal Product Code ) Comment    
transactionTable : string = `CREATE TABLE IF NOT EXISTS transactions (
        id INTEGER PRIMARY KEY,
        date TEXT,
        quantity REAL,
        unitCost REAL,
        reason VARCHAR,
        upc TEXT,
        comment TEXT,
        product_id INTEGER,
        FOREIGN KEY(product_id) REFERENCES products(id));`;

        async createTables(){
          try {
            await this.database.executeSql(this.familyTable);
            await this.database.executeSql(this.locationTable);
            await this.database.executeSql(this.productTable);
            await this.database.executeSql(this.transactionTable);
          }catch(e){
              console.log("Error !");
          }
      }

        constructor(public sqlite :SQLite) {
          console.log('Hello DataServiceProvider Provider')

              this.sqlite.create({name: "data.db", location: "default"}).then((db : SQLiteObject) => {
                      this.database = db;
                  }, (error) => {
                      console.log("ERROR: ", error);
              }); 
    }

}

Does anyone has an idea how to fix it?

Upvotes: 1

Views: 2726

Answers (2)

AVJT82
AVJT82

Reputation: 73367

Your code won't work in browser when running ionic serve, because:

As per mentioned here

Cordova needs plugins to run in browser

And they are not added by default. So you can run the project with ionic cordova run browser


OR as mentioned in the comment as well, mock the plugin. Tried it and it worked:

in app module, mock the create:

import { SQLite  , SQLiteDatabaseConfig , SQLiteObject } from '@ionic-native/sqlite';

class SQLiteMock {
public create(config: SQLiteDatabaseConfig): Promise<SQLiteObject> {
    return new Promise((resolve,reject)=>{
      resolve(new SQLiteObject(new Object()));
    });
  }
} 

Mark it in providers like:

{provide: SQLite, useClass: SQLiteMock},

Create a file sql.js file in the folder and copy the content from here: https://raw.githubusercontent.com/kripken/sql.js/master/js/sql.js

and add to your index.html:

<script src="assets/sql.js"></script>
<script src="build/polyfills.js"></script>
<script src="build/main.js"></script>

Now your function should work just fine. Going the further steps, I suggest you follow the link I provided before this code, i.e: https://www.techiediaries.com/mocking-native-sqlite-plugin/

Upvotes: 1

Tyler B. Joudrey
Tyler B. Joudrey

Reputation: 491

One thing you could look into is whether the constructor is being run before the async function in your code. If so look into implementing something along the lines on ngOnInit.

Upvotes: 1

Related Questions