I don't get Global Variables in ionic 2


#1

This is what i have:

providers/global/global.ts

import {Injectable} from 'angular2/core';

@Injectable()
export class Global {
  public background: string;
  constructor() {
    this.background = 'yellow';
  }

  setBackground(value) {
    this.background = value;
  }

  getBackground() {
    return this.background;
  }
}

pages/home/home.ts

import {Page, NavController, Alert, ActionSheet} from 'ionic-angular';
import {ConfigPage} from '../config/config';
import {Global} from '../../providers/global/global';

@Page({
  templateUrl: 'build/pages/home/home.html',
  providers: [Global]
})
export class HomePage {
  private bg: string;
  constructor(private nav: NavController, private global: Global) {
    this.bg = global.getBackground();
  }
}

and in the home.html i have [ngClass]="bg"

pages/config/config.ts

import {Page, NavController} from 'ionic-angular';
import {Global} from '../../providers/global/global';

@Page({
  templateUrl: 'build/pages/config/config.html',
  providers: [Global]
})
export class ConfigPage {
  private bg: string;
  constructor(private nav: NavController, private global: Global) {
    this.bg = global.getBackground();
  }

  onChange($event) {
    this.global.setBackground($event);
    console.log(this.global.getBackground());
  }
}

The global variable is working, the problem is that get reseted every time, when i go to the config page and set the global variable to another color with the onChange() function using a select, works… but when i go back to the home page the global variable reset to yellow, and then if i go to config page is yellow too.

What i am doing wrong? i don’t get it.


#2

config.ts

remove providers: [Global]

Or even better, add provider only to main app class, and then just inject it in other classes/pages.


#3

Oh, i tried with main app class but had some troubles, now is working, but…

the home background is not updated, only the config background.

How can i do to refresh the construct part?

  constructor(private nav: NavController, private global: Global) {
    this.bg = global.getBackground();
  }

Becouse global.getBackground() is updated but not this.bg

Thanks


#4

You mean this:
onChange($event) { this.global.setBackground($event); console.log(this.global.getBackground()); }

add this.bg = $event;

or in view use [ngClass]="global.getBackground()"


#5

Wow, how is posible i never tried [ngClass]="global.getBackground()"

Sorry for that noob questions, and thanks!