0

When I use SQLite, need re-open the dataase all time, andi this is too bad. How I can create/set a global variable with SQLite instance to share it between components?

Simple example:

app/app.ts

export class MyApp {
    constructor(public platform: Platform) {
        this.platform.ready().then(() => {
            @SetGlobal();
            let databaseInstance = new SQLite();
        });
    }
}

home/home.ts

export class HomePage {
    constructor(public platform: Platform, databaseInstance) {
        databaseInstance.then(() => {
            databaseInstance.executeSql('create table demo(name VARCHAR(32))', {}).then(() => {
            }, (err) => {
                console.error('Unable to execute sql: ', err);
            });
        }, (err) => {
            console.error('Unable to open database: ', err);
        });
    }
}
Jorge Olaf
  • 4,810
  • 8
  • 35
  • 70
  • You can use a service for that, just hold the connection on this service. – dlcardozo Mar 09 '17 at 19:35
  • What you suggest is that you use a provider to share the database instance, but every time you instantiate the provider, it will re-open the database, so it is not optimal. – Jorge Olaf Mar 09 '17 at 19:43
  • 1
    If you add that provider to your `app.module.ts` it will be a singleton provider, just be aware to don't put that service as a provider somewhere else. – dlcardozo Mar 09 '17 at 19:45
  • Can you write you answer with a code example?, please :D thanks! – Jorge Olaf Mar 09 '17 at 19:50
  • @OlafErlandsen you can see an example here http://stackoverflow.com/questions/36158848/what-is-the-best-way-to-declare-a-global-variable-in-angular-2-typescript and here http://stackoverflow.com/questions/35993778/angular-2-implementation-of-shared-services – Reza Mar 09 '17 at 19:56
  • 1
    @OlafErlandsen done, hope it helps. – dlcardozo Mar 09 '17 at 20:19
  • Thanks! im trying you example ;) – Jorge Olaf Mar 09 '17 at 20:59

1 Answers1

1

Main idea is to just hold the connection in a shared service, to be sure that you have only one connection alive. If you only provide this service on your app.module.ts this service will be a singleton instance and that is what you want.

Database service:

@Injectable()
export class DatabaseService {

    public instance = null;

    constructor(){
        this.instance = new SQLite();
    }
}

app.module.ts:

@NgModule({
  ...
  providers: [
    ...
    DatabaseService
  ]
})
export class AppModule {}

home.ts:

export class HomePage {
    constructor(public platform: Platform, dbService: DatabaseService) {
        dbService.instance.then(() => {
            dbService.instance.executeSql('create table demo(name VARCHAR(32))', {}).then(() => {
            }, (err) => {
                console.error('Unable to execute sql: ', err);
            });
        }, (err) => {
            console.error('Unable to open database: ', err);
        });
    }
}
dlcardozo
  • 3,583
  • 1
  • 13
  • 21