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.
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.
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)
}
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.