I am trying to make a singleton to get two variables from different components, these variables are defined by a component that is always executed before the others.
The problem I have is that the Singleton instance is not saved and when accessing it from another component it creates a new one, thus losing the variables that it had saved.
Below I attach the code of the singleton class, how I set the variables and how I try to get them from the other 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() from home.component.ts prints var1=example1 and var2=example2, instead in call.component.ts prints var1='' and var2=''.