Is there a way to access variables stored within a Singleton object?

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing global enumerations within VueJS

Is there a way to effectively utilize global enums in Vue or declare them differently? My current setup is as follows: Within my types/auth.d.ts: export {}; declare global { enum MyEnum { some = "some", body = "body", o ...

Drop the prohibited cursor before dragging

https://i.sstatic.net/WIBWr.jpg Is there a way to change the cursor behavior during element drag using HTML5 default drag and drop with TypeScript? I have tried various methods like changing from ev.target.style.cursor to "grab" cursor, adjusting dropEffe ...

Unit testing in Angular - testing the ng-content directive

I'm facing a challenge with my dynamic expansion panel component: <div class="expansion-panel"> <ng-content></ng-content> </div> When using this component, the structure would look like this: <expansion-panel> ...

What is causing the ng-container and bindings comments to display in the HTML of the deployed Angular Component?

I'm currently working on an Angular 12 application that integrates Bootstrap for a navbar displaying menu items. Some of these menu items have dropdowns with submenus, while others do not. To manage the HTML logic based on the presence of submenu item ...

Bringing together the functionality of tap to dismiss keyboard, keyboard avoiding view, and a submit button

On my screen, there's a big image along with a text input and a button at the bottom. The screen has three main requirements: When the user taps on the input, both the input and button should be visible above the keyboard The user must be able to ta ...

Error: Invalid connection string for ELF Lambda detected

Having an issue with a lambda function that connects to a remote MongoDB on an EC2 instance using TypeScript. While I can connect to the database locally, there is an ELF error when running in lambda. It seems to be related to mismatched binaries of npm pa ...

Using ngFor in Angular to apply a function to a variable

Imagine I have two tables: one for Books and one for Authors. The Author table contains a reference to the ID of a book. In my Angular project, I aim to iterate through the list of Authors and then iterate through the books written by each author: <di ...

The Bootstrap modal I implemented is opening correctly, but for some reason, the form inside is not appearing

I created the AddJokeModalComponent to streamline the process of opening a form without duplicating code in every component. Below is the modal structure: <ng-template #addJokeModal> <div class="modal-content my-custom-modal"> ...

Error with Google Maps in Ionic Capacitor (@capacitor/google-maps)

I attempted to integrate Google Maps into my ionic capacitor angular project by following their official guide. However, upon building the project, I encountered the subsequent error: Error: node_modules/@capacitor/google-maps/dist/typings/definitions.d.ts ...

Creating a websocket handler template for universal use

Currently, I am exploring different approaches to handling a generic websocket handler. The current implementation of the handler I have looks something similar to this: type WSMessage = { type: string; [key: string]: unknown; } type HandlerFunc = ...

Is the div's border linked to the routerlink directive?

Recently, I've been facing an issue with div elements using routerLink that are getting a blue border when clicked. It seems like there might be something obvious that I'm missing, whether it's a configuration in my browser or a CSS styling ...

What is the process for obtaining the complete URL using the getDownloadURL() function along with a token?

An error occurred due to an unresolved FirebaseStorageError: "storage/object-not-found". The message indicates that the object 'k91a73uzb99' does not exist in Firebase Storage. This type of error is categorized under FirebaseError with a code of ...

Updating the Mat Table Label Dynamically in Angular

Is there a way to dynamically change the value of a label in an Angular mat table with pagination without recreating the entire table? The goal is to update the header label without having to regenerate the whole table structure. For instance, in the tab ...

Troubleshooting: encountering empty page after deploying Angular 5 with .NET Core Web API

After attempting to deploy both an Angular 5 app and a .NET Core Web Api to the same server (IIS with .NET Core bundle), I encountered a frustrating issue where only a blank page would display upon starting up the application. Surprisingly, there were no c ...

Using Angular to automatically scroll to a section of the page when navigating to a targeted URL fragment

I'm currently working on coding an Angular project and I have a function that smoothly scrolls the page to a specific section. This function works flawlessly when triggered manually by me. However, my goal is to have the page automatically scroll to a ...

Updating the countdown label in NativeScript and Angular

I am currently working on a timer countdown component and have the following code: @Component({ moduleId: module.id, selector: 'time-countdown', template: `<StackLayout> <Label text="{{timeRemaining}}" ></La ...

Why do callbacks in Typescript fail to compile when their arguments don't match?

In my current project, I encountered a scenario where a React callback led to a contrived example. interface A { a: string b: string } interface B { a: string b: string c: string } function foo(fn: (a: A) => void, a: A) { fn( ...

Transmit information using express handlebars in a straightforward node application

Struggling to pass data from express handlebars to index.html? Check out my code below: server.js code: const express = require('express'); const app = express(); const expressHandlebars = require('express-handlebars'); const path = r ...

Struggling with setting up eslint in my typescript project

Below is the contents of my package.json file: { "devDependencies": { "@typescript-eslint/eslint-plugin": "^5.13.0", "@typescript-eslint/parser": "^5.13.0", "airbnb": "^0.0.2&qu ...

Press the inactive button to view the continuing effects

Currently, I am utilizing mat-icon for my buttons and would like to disable certain ones: <button mat-button [disabled]="disabledCondition()"> <mat-icon [routerLink]="['./settings']"> settings </mat-icon> </b ...