Using Angular and TypeScript/javascript singletons across multiple browser tabs

I am curious about whether the TypeScript singleton class, used as an MVC model object in my Angular application within one browser tab, would be different from or the same as the singleton loaded into another tab within the same browser instance.

The setup is somewhat like this (a similar concept could be implemented in JavaScript):

[TypeScript]
class Budget {
    readonly name : string;

    private static instance: Budget;
    static getInstance(name? : string) {
        if (!this.instance) {
            name = name ? name : "no name";
            this.instance = new Budget(name);
        }
        return this.instance;
    }
    private constructor(name : string) {
      this.name = name;
    }
 }

In my project, the main "Budget" object is designed as a singleton to simplify access to various data elements, class instances, and more. This Budget object consists of approximately 40 other component classes that need to interact with each other, and the Budget object provides a way for each class instance to access the necessary components. The Singleton pattern allows me to write code like Budget.getInstance().getAccount("foo") without having to keep a reference to a Budget instance in every sub-class. This approach significantly simplifies my coding process.

My concern is whether a user could open two separate budgets in different tabs of a browser (for example, Chrome), each referring to distinct instances of the Budget object with unique names. (The singleton instance is populated with data by a rails backend based on the selected budget for editing.) I can envision scenarios where it would be advantageous for a user to work with two different budgets simultaneously in the same browser window, each in its own tab. However, this would not be feasible if there is only one accessible Budget object shared across all tabs in the browser.

Answer №1

Sharing JavaScript objects between tabs can be achieved when the second tab is opened from the first tab using the window.open() method, which provides access to the window object of the newly opened tab.

While there isn't a built-in Angular solution for this task, you can still accomplish it by leveraging native JavaScript:

  • To start, open the browser's console and execute:
    const newTab = window.open('', '_blank');
  • Create an object on the first tab with: const obj = {};
  • Share the object with the second tab using: newTab.obj = obj;
  • In the second tab, make changes to the object by entering: obj.prop = 'updated';
  • Upon checking in the first tab using: obj, you will see that the object has been modified by the second tab

If your concern pertains to independently opened tabs, regrettably, achieving this cross-tab object sharing is not feasible.

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

Having trouble with Javascript fetch() not receiving the correct JSON data from the local server

My Django backend is serving JSON data, but I'm encountering some unexpected results. When using curl 127.0.0.1:8000/posts/, the response includes: [ { "title": "This is a title", "body": "Body :)", "pub_da ...

Using AngularJS to access the properties of a header within a $http request

As I navigate through the github API's pagination documentation, I am attempting to retrieve event items and extract the Link header (as recommended) in order to construct the pagination. However, I am facing difficulty in understanding how to work wi ...

Having difficulty verifying the elements of an associative array after using json_decode

My goal is to implement form validation in PHP and send any errors to the AJAX call. I have structured the form inputs as an array with named indexes from the AJAX call to the PHP controller. Upon decoding it using json_decode() in PHP, my intention is to ...

Eliminate the hovering effect from images that are hyperlinked

I am feeling incredibly desperate as I have spent hours searching the internet for a solution with no success. When it comes to text links, I have included the following CSS code: a:hover img { border-bottom: none !important; } However, this code is als ...

Determine the frequency values and coordinates of the normal distribution curve (X and Y axes)

I have successfully implemented the Histogram chart using react-plotlyjs. The graph is working fine but now I need to draw the normal distribution curve using X and Y axes. While I have the coordinates for the X axis, the Y axis values are automatically ca ...

Encountering a service error that results in the inability to read properties of undefined when passing a method as a

Whenever I attempt to pass a service function as a parameter to another function, an error 'Cannot read properties of undefined myService' occurs during execution. However, calling this.myService.method() individually works perfectly fine without ...

Invoke OnSelectedIndexChanged from GridView prior to any other function execution

In my scenario, there are two GridViews available. The first GridView allows the user to select a row, based on which a corresponding list will be displayed according to the selected GridView ID. First Grid: https://i.stack.imgur.com/d0OKq.png Second Gri ...

Retrieving a data value using a specific key within a JavaScript object

Trying to retrieve a specific value by providing the literal key in a JavaScript object. The image below indicates that "filter" is equal to "Approved", sourced from reimb_status_description. Line 6 of code assigns filter to the value. const filter = Obj ...

What is the method for determining the dimensions of the rectangle that the camera can capture at a specific location?

In my latest project, I developed a small three.js application that showcases the movement of multiple circles from the bottom to the top of the canvas: let renderer, scene, light, circles, camera; initialize(); animate(); function initialize() { re ...

Alternative to updating object coordinates in Fabric JS 1.7.9 - seeking solutions for migration challenges

Update: JSFiddle: https://jsfiddle.net/Qanary/915fg6ka/ I am currently working on implementing the `curveText` function (found at the bottom of this post). It was functioning properly with `fabric.js 1.2.0`, but after updating to `fabric.js 1.7.9`, I not ...

Guide on testing a function with a dependency in Angular through unit testing

Attempting to dive into unit testing, I have grasped some of the basics. However, my current challenge lies in testing a method within my code. This particular method involves calling a function from oidc-client.js that handles user sign-ins. My spec fi ...

Manipulate and structure personalized date string using Moment.js

Trying to retrieve the month and year from a customized date string Wed Dec 24 00:00:00 -0800 2014 with Moment.js. Came across this previous solution: How to parse given date string using moment.js? however, the accepted answer is causing an error. Expec ...

Creating a CDK resource in TypeScript if it doesn't already exist

Recently, I set up a DynamoDB table in my CDK project to be used by lambdas within the same project. Everything was working fine until we needed to delete the stack with the retain resource option set to true for the table. However, when attempting a fres ...

Exploring the implementation of window.addEventListener within an Angular project

I am currently working on testing a method in Angular using Jasmine. However, I am running into an issue with triggering the mouse event (specifically when the browser back button is clicked). Below is the code snippet I'm working with: navigate() { ...

Transform the text column into JSON format

We currently have a resource bundle/properties formatted as follows: [tag1] server1 server2 [tag2] server3 server4 [tag3] server5 server6 [No Software Installed] server7 [tag2] server8 [tag5] server9 [tag1] server10 server11 [tag3] server12 server13 serve ...

CASL user update has been refreshed

My CASL implementation is quite basic and I've noticed that the documentation lacks detail. The code I'm using is essentially a copy-paste from the docs: import { abilitiesPlugin } from '@casl/vue' import defineAbilitiesFor from &apos ...

What is the best way to dynamically load and render a component within another component in Angular?

I have been working on creating a custom Grid component that allows me to pass and render other components. I have successfully developed the Grid component and am loading it dynamically in my dashboard.component.ts. Below is the template for my Grid. < ...

BotFramework-Webchat Middleware: defining custom CSS class names

My goal is to dynamically assign CSS class names based on the card type to the corresponding HTML element. I've achieved this by utilizing the [AdaptiveCard.customCssSelector] 1 attribute. For example, you can simply include builder.card.customCssSel ...

The attribute 'id' cannot be found in the class 'Foods'

After examining my code below, I am attempting to remove clients from my data table by using checkboxes. Whenever I check a checkbox, I notice in the console that the object's properties are retrieved from the database. My goal is to delete by id, but ...

Unable to view cross domain cookies within the browser's development tools

I am currently working on a web application that has an Angular front end running on http://localhost:4200 and a NodeJs backend running on http://localhost:3000. When a user successfully logs in, a cookie is set from the backend containing a token. However ...