Global variables on ionic 2

Thanks @rapropos , I am trying your code right now, although I don’t understand fully.
So here’s my global-vars.ts with your code:

import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage';


@Injectable()
export class GlobalVars {
  ready: Promise<any>;
  private _isWebIntegration: boolean;

  constructor(private _storage: Storage) {
    this.ready = Promise.all([
      this._storage.get('isWebIntegration').then((wip) => this._isWebIntegration = wip),
      // &c &c for other similar stuff
    ]);
  }

  // don't call any of these until this.ready resolves

  isWebIntegration(): boolean {
    return this._isWebIntegration;
  }

  setWebIntegration(wip: boolean): Promise<any> {
    this._isWebIntegration = wip;
    return this._storage.set('isWebIntegration', wip);
  }
}

but when I add the dependency injection in weightlevel.ts, I get an error that was not there before. I added the import line, the @Component({...providers: [GlobalVars] the constructor(... public globalVars: GlobalVars and as follows:

import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { ComparePage } from '../compare/compare';
import { ViewChild } from '@angular/core';
import { Slides } from 'ionic-angular';
import { LocalStorageService } from 'angular-2-local-storage';
import { GlobalVars } from '../../providers/global-vars';


@Component({
    selector: 'page-weightlevel'
    , templateUrl: 'weightlevel.html'
    , providers: [GlobalVars]
})
export class WeightlevelPage {

    name: string;
    firstNavParam: boolean;
    data:any = {};
 

    constructor(
        public navCtrl: NavController,
        public navParams: NavParams,
        private storageService: LocalStorageService
        , public globalVars: GlobalVars
    ) {
        console.log("Executing Weightlevel.ts");
        this.name = 'Max';
        // this.globalVars.addGlobalVar("isWebIntegration", false);

        if (storageService.get('firstNavParam') === 'no') {
            this.firstNavParam = false;
        } else {
            this.firstNavParam = true;
        }
        this.data.shareoptions = ['Facebook', 'Twitter', 'Email'];
        this.data.techniqueText = "Intermediate+";
        this.data.frequScaleWording = ['Once a year or  +','Once a month or  +', 'Once a week or  +', 'Once a day or  +'];    
        this.data.fitnessWording = ['Couch potatoe', 'Healthy', 'Sporty', 'Top athlete'];
        this.data.levelName = ['Total noob', 
        'Noob', 
        'Beginner', 
        'Intermediate-', 
        'Intermediate', 
        'Intermediate+', 
        'Good', 
        'Good+', 
        'Very good', 
        'Excellent', 
        'Pro surfer!'];
        this.data.slideIndex = 0;
        this.data.slideTitle = ['Gender',
        'Date of birth',
        'Weight',
        'Height',
        'Technique',
        'Frequency',
        'Fitness',
        'Wetsuit'];
        this.data.slideTitleTranslationIDs = [];
        for (var i = 0; i < this.data.slideTitle.length; i++) {
            this.data.slideTitleTranslationIDs[i] = 'general.' + this.data.slideTitle[i].toLowerCase().replace(/\s/g, '');
        }
    }

    @ViewChild(Slides) slides: Slides;

    ionViewDidLoad() {
        console.log('ionViewDidLoad WeightlevelPage');
    }
  
    goToSlide() {
        this.slides.slideTo(2, 500);
    }
}

and I now get this error:

Runtime Error
Error in ./MyApp class MyApp - caused by: No provider for Storage!
Stack
Error: DI Error

Another question:
Do you think this or this (putting global variables in a ts file) is a good solution? It looks simpler for sure.

Don’t do this. It will completely defeat the entire purpose, because a new instance will be spun up for every component. Put it only in the app module.

I assumed you were using ionic-storage (which you probably should be). If you insist on sticking with that other storage library, use it in place of Storage.

This would all probably go a lot more smoothly for you if you can find the time to sit down and go through the Hall of Heroes and the Ionic conference app.

Hi @rapropos. Ok thanks for your help.
I am gonna do what you suggest and go through both tutorials.

Thanks !

1 Like

Hi @rapropos,

thanks for making me aware of Ionic Storage, it’s seem nice, but it’s a real pain to rewrite all my calls to Storage in a Promise scope! I am not sure I’m ready to take the step…
But I am giving it a try for this GlobalVars component. So I have your code:

import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage';

@Injectable()
export class GlobalVars {
	ready: Promise<any>;
	private _isWebIntegration: boolean;

	constructor(
		private _storage: Storage
	) {
		this.ready = Promise.all([
			this._storage.get('isWebIntegration').then((wip) => this._isWebIntegration = wip)
			// &c &c for other similar stuff
			]);
	}

	// don't call any of these until this.ready resolves

	isWebIntegration(): boolean {
		return this._isWebIntegration;
	}

	setWebIntegration(wip: boolean): Promise<any> {
		this._isWebIntegration = wip;
		return this._storage.set('isWebIntegration', wip);
	}
}

I am calling it from my component weightlevel.ts:

import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { ComparePage } from '../compare/compare';
import { ViewChild } from '@angular/core';
import { Slides } from 'ionic-angular';
import { LocalStorageService } from 'angular-2-local-storage';
import { GlobalVars } from '../../providers/global-vars';

@Component({
    selector: 'page-weightlevel'
    , templateUrl: 'weightlevel.html'
})
export class WeightlevelPage {

    @ViewChild(Slides) slides: Slides;

    name: number;
    firstNavParam: boolean;
    data: any = {};
    // data: Object = {};

    
    // data.techniqueText: string;
    // data.frequScaleWording: string[];
    // data.fitnessWording: string[];
    // data.levelName: string[];

    constructor(
        public navCtrl: NavController
        , public navParams: NavParams
        , private storageService: LocalStorageService
        // , private MathService: MathService
        , public globalVars: GlobalVars
    ) {
        
        console.log("Executing Weightlevel.ts");
        this.globalVars.setWebIntegration(true).then( (shit) => { console.log( "isWebIntegration is set to = ", this.globalVars.isWebIntegration())} );

But when I set the boolean value, I have run the app twice to see the right value in the console.log (see the screenshot, the value is true in IndexedDB, and false in the console):

Why does it need to run twice to get the actual IndexedDB value ?

Is there some sort of race condition setting up the database?