Use provider in app.component.ts

Hello,

I want to put my SQLite Code in a separate file. The file looks like this:

sqlitehelper.ts:

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

@Injectable()
export class SQLiteHelper{

    private _db: any;

    constructor(){
        this._db = new SQLite();
        console.log("SQL CONSTRUCTOR");
    }

    private dbOpen(){
        this._db.openDatabase({
            name: 'data.db',
            location: 'default'
        }).then(() => {
            console.log("SQL OPEN");
        }, (err) => {
            console.error('Unable to open database: ', err);
        });
    }

    public dbCreateTables(){
        console.log("SQL CREATE TABLES");
        this.dbOpen();
        this._db.executeSql('CREATE TABLE IF NOT EXISTS medis(id INT PRIMARY KEY, wirk TEXT)', {}).then(() => {
            console.log("SQL TABLE CREATED");
        }, (err) => {
            console.error('Unable to execute sql: ', err);
        });
        this._db.close();
    }
}

in the app.module.ts I add it as provider:

import { SQLiteHelper } from '../providers/sqlitehelper';
[...]
providers: [SQLiteHelper]

my app.component.ts looks like this:

import { Component, ViewChild } from '@angular/core';
import { Nav, Platform } from 'ionic-angular';
import { StatusBar, Splashscreen } from 'ionic-native';
import { SQLiteHelper } from '../providers/sqlitehelper';

import { Page1 } from '../pages/page1/page1';
import { Page2 } from '../pages/page2/page2';


@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  @ViewChild(Nav) nav: Nav;

  rootPage: any = Page1;

  pages: Array<{title: string, component: any}>;

  constructor(public platform: Platform, public db: SQLiteHelper ) {
    this.initializeApp();

    this.pages = [
      { title: 'Page One', component: Page1 },
      { title: 'Page Two', component: Page2 }
    ];

  }

  initializeApp() {
    this.platform.ready().then(() => {
        StatusBar.styleDefault();
        Splashscreen.hide();
        this.db.dbCreateTables;
    });
  }

  openPage(page) {
    this.nav.setRoot(page.component);
  }
}

I get the log from the constructor but it doesn’t execute the dbCreateTables methode.

shouldn’t it be this.db.dbCreateTables() in app.component.ts?

1 Like

Yes you are right, was my fault. but didn’t get any error massage, and didn’t saw the error.

thx for help

if we shouldn’t call this.db.dbCreateTables() in app.component.ts how should we call …?

How should I call the function?

Please tell then how it must be call ???

The issue is not the name of the function but the omission of () which is needed to trigger the function call