Update global variable in all views


#1

I’m working on an app that the user can change the app colour, for this I’m using a global.ts for declaring the variables and in a popover I have the options to change the colours.

global.ts

	export const Global = Object.assign({
		cPrimary: 'primary',
		cPrimaryBlue: 'primaryBlue',
		cLight: 'light',
		cDark: 'dark',
		mainColor: 'dark'
	});

event-popover.ts

	import { Global } from './../../app/global';
	import { EventPage } from './../event/event';
	import { Component } from '@angular/core';
	import { NavController, NavParams, ViewController } from 'ionic-angular';

	@Component({
	selector: 'page-event-popover',
	templateUrl: 'event-popover.html',
	})
	export class EventPopoverPage {

        constructor(public navCtrl: NavController, public navParams: NavParams, public viewCtrl: ViewController) {
		}

		changeColor(c){
			if (c = 'light'){
				Global.mainColor = Global.cLight;
				console.log(Global.mainColor);
			}
		}
	}

event-popover.html

		<ion-col>
		    <button ion-button="dot" class="dot-light" (click)="changeColor('light')"></button>
		</ion-col>

One of the views that need change the colour:
event.ts

	import { Global } from './../../app/global';

	@Component({
		selector: 'page-event',
		templateUrl: 'event.html',
	})
	export class EventPage {
		public color = Global.mainColor;
    }

event.html

	<ion-header>
		<ion-navbar color="{{color}}">
			<ion-title>Home Event</ion-title>
			<button ion-button icon-only (click)="eventPopover($event)" color="none" item-right><ion-icon name="md-menu" color="light"></ion-icon></button>
		</ion-navbar>
	</ion-header>

My function changeColor() is working on change the value of the Global.mainColor but isn’t updating the variable on the views… What is missing?


#2

I would suggest something along these lines:

export interface Theme {
  primary: string;
  primaryBlue: string;
  light: string;
  dark: string;
  main: string;
}

@Injectable()
export class ThemeService {
  theme = new BehaviorSubject<Theme>({
    primary: 'primary',
    primaryBlue: 'primaryBlue',
    light: 'light',
    dark: 'dark',
    main: 'dark'
  });

  setMainColor(c: string): void {
    let t = this.theme.value;
    t.main = c;
    this.theme.next(t);
  }
}

@Component()
export class EventPage {
  color: string;

  constructor(themes: ThemeService) {
    themes.theme.subscribe(theme => this.color = theme.main);
  }
}

#3

It says: [ts] Cannot find name ‘BehaviorSubject’.


#4

Like anything else, you need to import it.


#5

I wasn’t finding from where to import.

  constructor(themes: ThemeService) {
    themes.theme.subscribe(theme => this.color = theme.main);
  }

themes doesn’t have theme, only (dark, light, primary and primaryBlue)


#6

Your IDE should find it for you. It’s part of rxjs.

In my version, it does. themes.theme is the BehaviorSubject responsible for conveying changes to the theme to all the parts of the app that need to know about them.