I'm currently working on creating a singleton to retrieve two variables from different components. These variables are defined in a component that always runs before the others.
The issue I'm facing is that the Singleton instance isn't being maintained, so when accessed from another component, a new instance is created resulting in the loss of the saved variables.
Below is the code for the singleton class, how the variables are set, and the attempt to retrieve them from another component:
Singleton.ts
export class Singleton {
private static instance: Singleton = new Singleton();
private var1: string = '';
private var2: string = '';
private constructor() {}
public static getInstance() {
if (!this.instance) {
this.instance = new Singleton();
}
return this.instance;
}
public getVar1():string {
return this.var1;
}
public getVar2():string {
return this.var2;
}
public setVar(var1:string, var2:string):void {
this.var1= var1;
this.var2 = var2;
}
}
home.component.ts
ngOnInit() {
var var1 = "example1"
var var2 = "example2"
let global = Singleton.getInstance();
global.setVar(var1, var2);
console.log(global);
}
call.component.ts
ngOnInit() {
let global = Singleton.getInstance();
this.var1 = global.getVar1();
this.var2 = global.getVar1();
console.log(global);
}
The console.log() in home.component.ts displays var1=example1 and var2=example2, but in call.component.ts it shows var1='' and var2=''.