Search code examples
javascriptvariablestabsionic2injectable

Global variables Ionic 2


I'm having some difficulties with Ionic 2 and setting up global variables. The structure of my app is as follows:

Main app
  |
  |--- Page1 (Info)
  |--- Page2 (Map)
  |--- Page3 (List)
         |
         |--- ItemTabsPage
                |
                |---tab1
                |---tab2
                |---tab3

My intention is to show a list in Page3, and once one item is selected, to show additional information in tabs.

I send the information from Page 3 to the page with the tabs using:

itemTapped(event, item) {
    this.nav.push(ItemTabsPage, {
      item: item
    });
  }

The problem is that I can't do the same to send the info to the child tabs. I would like to show different information depending on which item is selected. I have tried defining an injectable globalVars.js to store the value in a variable:

import {Injectable} from 'angular2/core';

@Injectable()
export class GlobalVars {

  constructor(myGlobalVar) {
    this.myGlobalVar = "";
  }

  setMyGlobalVar(value) {
    this.myGlobalVar = value;
  }

  getMyGlobalVar() {
    return this.myGlobalVar;
  }

}

and then updating the code of itemTapped in the list as follows:

itemTapped(event, item) {
        this.nav.push(ItemTabsPage, {
          item: item
        });
        this.globalVars.setMyGlobalVar(item);
      }

However, I always get the same error:

Uncaught EXCEPTION: Error during evaluation of "click"
ORIGINAL EXCEPTION: TypeError: Cannot read property 'setMyGlobalVar' of undefined

The code for page3 is:

import {Page, NavController, NavParams} from 'ionic-angular';
import {ItemService} from '../services/ItemService';
import {ItemTabsPage} from '../item/item-tabs/item-tabs';
import {GlobalVars, setMyGlobalVar} from '../../providers/globalVars';

import {Http} from 'angular2/http';
import 'rxjs/add/operator/map';

@Page({
  templateUrl: 'build/pages/item-list/item-list.html',
  providers: [ItemService]
})

export class ItemListPage {

  static get parameters() {
    return [[NavController], [NavParams], [Http]];
  }

  constructor(nav, navParams, http, globalVars) {
    this.nav = nav;
    // If we navigated to this page, we will have an item available as a nav param
    this.selectedItem = navParams.get('item');
    this.http = http;
    //this.items = null;
    this.globalVars = globalVars;


    this.http.get('https://website-serving-the-info.com/items.json').map(res => res.json()).subscribe(data => {
        this.items = data.items;
        },
      err => {
          console.log("Oops!");
    });

  }

  itemTapped(event, item) {
    this.nav.push(ItemTabsPage, {
      item: item
    });
    this.globalVars.setMyGlobalVar(item);
  }
}

Anyone have any suggestion? My Ionic installation is:

Cordova CLI: 6.1.1
Gulp version:  CLI version 3.9.1
Gulp local:   Local version 3.9.1
Ionic Framework Version: 2.0.0-beta.4
Ionic CLI Version: 2.0.0-beta.25
Ionic App Lib Version: 2.0.0-beta.15
OS: Distributor ID: LinuxMint Description:  Linux Mint 17.3 Rosa 
Node Version: v5.11.0

Solution

  • You're on the right track. And some of the other answers will work, but the Ionic team is recommending you not use globals via a globals file. Instead, they recommend the use of Providers (as you're attempting to do).

    You're provider is missing the actual variable declaration.

    @Injectable()
    export class GlobalVars {
        myGlobalVar: string = ''  // this is the line you're missing
    
        constructor(myGlobalVar) {
            this.myGlobalVar = "";
        }
    }
    

    You should also note that you are not exporting the function setMyGlobalVar(). You are exporting the class GlobalVars which contains the function setMyGlobalVar().

    I believe if you make those changes it should work.

    edit I'd also be careful of this line this.globalVars = globalVars; in your Page3. This will cause a rewrite of your globalVars each time Page3 is created.