Declaring one variable and use this common variable in all pages

In ionic v1 I was declaring my global variables in app.js but I am not getting any picture where to declare my global variable in ionic v2.

Particular I want to declare a puchdb variable and use it in all js.

var localDB = new PouchDB(“dbname”);
var remoteDB = new PouchDB(“http://username:password@”);

I was declaring it bellow the following line and using in external controllers and services js file. But here I am confused. There must be some way.

var app = angular.module(‘starter’, [‘ionic’]);

Create a service and inject it where you need it.

@willb is right, in ionic 2 all components have isolated scope, in order to have available a variable you need to create a service to be able to comunicate data between components.

But, and this is a big one, if you just make a service and inject it where you need you will not have a global service, you will get multiple instances of the same service, in order to make it a global one that passes state between components, you have to declare it as a singleton provider in your @app component like this:

import {App, IonicApp, Platform} from 'ionic/ionic';
import {Config} from './services/config'
import {DB} from './services/db'
import {MasterService} from './services/master-service'
  templateUrl: 'app/app.html',
  providers: [Config, DB, MasterService]

If you need to have a database variable to be able to make a query, you should make a database service, mine is DB, then you can attach some common behavior to make querys, like transactions…

Here’s an example in one of my old posts: Ionic 2 SqlStorage transactions, how to use?


Thank you response @luchillo17 and @willb . Trying to implement it.

Yeah it worked!! Thanks @luchillo17

3 days to test this is a little long :stuck_out_tongue:, good it was helpful.

No, just had other stuffs to do so it took this long. Thanks anyway @luchillo17 .