How to change value of global variable on any files in Ionic?

Hi,

I’m new to Ionic/typescript. Would like to know how to have a global variable that can be changed/retrieved on any files on Ionic app. Tried different methods but it doesn’t work.

Basically this is to set/get the value of a refresh token from oauth2. The value needs to be overwritten and retrieved per each API call.

What’s the easiest way to implement this? Please help.

Thanks in advance.

Read about service providers.

Thanks for your response. Learned that it’s easier to implement this via localStorage.

Thanks!

Depends on what you mean by easier. It’s slower and uses more overhead than defining a service provider. But it’s only a couple lines of code because the library does the work.

This is super easy

Create a provider first. ionic g provider global

Declare your variables in new Provider

import { Injectable } from '@angular/core';
/*
  Generated class for the GlobalProvider provider.
*/
@Injectable()
export class GlobalProvider {

  public myGlobalVar: string;

Use this in other .ts files like below

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

constructor( public global: GlobalProvider) {
....


myfunction1(){
   this.global.myGlobalVar="setting global val"
}


myfunction2(){
   alert(  this.global.myGlobalVar)
}

use in template file like below

<ion-content>
<h1>{{ global.myGlobalVar }} </h1>

Dont forget this to set in app.module.ts

providers: [
   // StatusBar,
  //  SplashScreen,
   // InAppBrowser,
   // SocialSharing,
   // AdMobFree,
    //DateAndTime,
    { provide: ErrorHandler, useClass: IonicErrorHandler },
  //  FeedService,
    GlobalProvider
  ]
10 Likes

Storage of any sort should only be used for things you want to persist across app restarts. Simply sharing data in a single run across pages is a bad fit for it.

2 Likes

Nice Solution! Great!

Show. Funcionou perfeitamente! Obrigado rashnk