最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Global variables Ionic 2 - Stack Overflow

programmeradmin4浏览0评论

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('.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

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./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
Share Improve this question edited Apr 25, 2016 at 15:13 Jumy Elerossë asked Apr 25, 2016 at 15:07 Jumy ElerossëJumy Elerossë 1892 gold badges3 silver badges12 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 7

The easiest way I use is to create a file app/global.ts

export var global = {
    myvar : 'myvar 01',
    myfunction : function(msg) {
        alert(msg);
    }
};

Then import and use freely in other classes:

import {global} from "../../global";

constructor() {        
    global.myfunction('test');
}

and if you want to use this global to ponent HTML page as below

    export class HomePage {
        Global: any = Global;

now it is available in HTML as below

    <div [style.display]="Global.splash ? 'flex': 'none'" >         

You're on the right track. And some of the other answers will work, but the Ionic team is remending you not use globals via a globals file. Instead, they remend 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.

I have exactly the same scenario, and would like to share my approach.

my understanding is that, in ionic2, the injection is implemented as instance. which means each time you enter a page, a new instance of the injection is created.

so direct access to a static value does not fit here; you have to somehow bridge the gap.

my approach goes as this:

you still defined a static value in your service provider, yet you define instance "getter", and "setter" for that value.

in your page implementation, you inject the service as a parameter of the constructor.

in the constructor, you have to "new" an instance of the service; and call the "getter", and "setter". see my code snippets below:

export class TransSender {
   static _count:number = 0;
   static _pushed:number = 0;
   ...

   public static setter(count:number, pushed:number,...) {
        TransSender._count = count;
        TransSender._pushed = pushed;
   }
   public get count(){
        return TransSender._count;
   }
   public get pushed(){
        return TransSender._pushed;
   }
   ... 
}

I actually provide a static collective setter for the service to get value from backend in a static way.

my page implementation runs likes this

import {TransSender} ...;

@Component({
    templateUrl: 'build/pages/basics/basics.html',  
    providers: [TransSender]
})

export class Page {
    ...  
    constructor(tSender: TransSender,...) {  
        ...
        tSender = new TransSender();
        TransSender.setter(1,2,3,4,5,6,7,8);
        console.log(tSender.count);
    } 
}

in your display (html), your will refer to tSender rather than TransSender

this might look a bit stupid. yet I can not find any other solution.

with the release of ionic2 Beta9, bootstrap was re-introduced into the frame. so I am exploring new possibilities

cheers

In your class ItemListPage, try this static parameters method before your constructor:

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

I am thinking that you are setting your globalVars variable in the constructor to 'undefined' and therefore you cannot call a function on something that is undefined.

You seem to inject the GlobalVars provider incorrectly in ItemLisyPage.

发布评论

评论列表(0)

  1. 暂无评论