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


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.

1 Like

Read about service providers.

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


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.
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(){"setting global val"


use in template file like below

<h1>{{ global.myGlobalVar }} </h1>

Dont forget this to set in app.module.ts

providers: [
   // StatusBar,
  //  SplashScreen,
   // InAppBrowser,
   // SocialSharing,
   // AdMobFree,
    { provide: ErrorHandler, useClass: IonicErrorHandler },
  //  FeedService,

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.


Nice Solution! Great!

Show. Funcionou perfeitamente! Obrigado rashnk