0

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=''.

Alvaro
  • 1
  • You are using the singleton pattern wrong here. Use a service which is provided in root, these are singleton services (only one instance lives in the entire app). If you want to use them in a reactive angular way, see this answer with a subject Observer Pattern: https://stackoverflow.com/questions/57355066/how-to-implement-behavior-subject-using-service-in-angular-8/57355485#57355485 – sagat Feb 23 '22 at 19:32
  • Not sure how you’re using this, but Angular has a really nice DI system that takes care of this for you. The problem here is probably that you are creating this thing in a component, then move to the next component. Problem is, first component gets destroyed, together with you class. If you really want to do this (and I wouldn’t), make sure you call the class in your app.component, as this component is never destroyed. – MikeOne Feb 23 '22 at 20:21

1 Answers1

-1

if you want the same value in another component then you need to use input and output decorators . check out below link

https://angular.io/guide/inputs-outputs

Robin Chauhan
  • 71
  • 4
  • 12