【问题标题】:How I can set a global variable in Ionic2?如何在 Ionic2 中设置全局变量?
【发布时间】:2017-03-10 03:59:03
【问题描述】:

当我使用 SQLite 时,需要一直重新打开数据库,这太糟糕了。 如何使用 SQLite 实例创建/设置全局变量以在组件之间共享它?

简单示例:

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);
        });
    }
}

【问题讨论】:

  • 您可以为此使用服务,只需在该服务上保持连接即可。
  • 你的建议是使用provider来共享数据库实例,但是每次实例化provider都会重新打开数据库,所以不是最优的。
  • 如果您将该提供程序添加到您的app.module.ts,它将是一个单例提供程序,请注意不要将该服务作为提供程序放在其他地方。
  • 你能用代码示例写下你的答案吗?请 :D 谢谢!
  • @OlafErlandsen 完成,希望对您有所帮助。

标签: cordova typescript ionic-framework ionic2


【解决方案1】:

主要思想是将连接保持在共享服务中,以确保您只有一个连接处于活动状态。如果您只在 app.module.ts 上提供此服务,此服务将是一个单例实例,这就是您想要的。

数据库服务:

@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);
        });
    }
}

【讨论】:

    猜你喜欢
    • 2019-06-13
    • 1970-01-01
    • 2013-08-16
    • 1970-01-01
    • 1970-01-01
    • 2019-12-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多