Angular local storage override problem

For system authentication purposes, I am storing the access token in the local storage. When User-A logs in, their access token is saved in the local storage without any issues. However, if User-B opens another tab of the same project and logs in, their access token ends up overriding User-A's in the local storage. This leads to the content on the User-A tab changing to User B's when reloaded.

Answer №1

Establish a unique identifier, such as a UUID, to distinguish users in your application.

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name = 'Angular';
  key: string = 'token';
  myItem: string;
  uniqueKey: number;
  localStorageParam: any;

  constructor() {
    this.uniqueKey = parseInt(Math.random() * 1000000);
    localStorage.setItem(this.key + '_' + this.uniqueKey, 'Some Value');
    this.localStorageParam = localStorage;
    this.myItem = localStorage.getItem(this.key);
  }
}

https://stackblitz.com/edit/angular-localstorage-fz9na6?file=src%2Fapp%2Fapp.component.ts

Alternatively, consider using sessionStorage for user-specific session data. Note that session data is lost when the session ends (e.g., user logs out, closes the tab). https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage

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

Working with Parse.com's REST API: Implementing skip and limit queries using JavaScript

Currently, I am in the process of retrieving data using Parse through the REST API in Javascript. Everything is working fine until I attempt to include a limit and an offset ("skip"). Here, you can find the documentation for using parameters with a REST ...

Do you know if there is a specific way to insert conditional template values?

Within my angular template (version 2.4.9), there is a specific element that I need to modify based on certain conditions: <div *ngIf="a || b || c || d || e">Remaining</div> Now, I am tasked with changing the static "Remaining" text in respon ...

Sending a form using ng-model with ng-repeat and ng-if conditions

How can I effectively submit a form in angular using ng-submit when also utilizing ng-repeat and ng-if? The issue arises with the disappearing of the input option containing ng-model due to ng-if. Below is a snippet of my code for better understanding: &l ...

Integrating Braintree with Angular for accepting Android Pay transactions

Currently facing a challenge with Braintree that I need help resolving. I have successfully set up Braintree to generate my client_token using my API, and created the drop-in feature as a test. Here is how I implemented it: (function () { 'use st ...

Tips for customizing the appearance of a specific mat-button component in an Angular project

In my Angular application, I have set up a scenario where users are presented with multiple choices through buttons. When a user clicks on a button, a specific component is displayed based on their choice. I am currently working on enhancing the styling of ...

Issue with selecting a value in React MUI and default value not being defined

Currently, I am working on creating a form in React using MUI and Formik. While implementing the select feature with default values fetched from an API object, I encountered issues where the select function was not working as expected. Strangely, I couldn& ...

Using the angular2-cookie library in an Angular 2 project built on the rc5 version

Starting a new angular2 rc5 project, I wanted to import the angular2 cookie module. After installing the module with npm, I made changes to my angular-cli-build.js file : npm install angular2-cookie edited my angular-cli-build.js file : module.exports ...

Angular is encountering a circular dependency while trying to access a property called 'lineno' that does not actually exist within the module exports

I am working on an Angular project and using the Vex template. My project utilizes Angular 9 and Node.js v15.2.0. Every time I run the project with the command ng serve -o, it displays a warning message. https://i.stack.imgur.com/8O9c1.png What could b ...

Sharing a let value within *ngFor loop from template to .ts file - here's how

Is it possible to use the async pipe to share the interpolation value {{ticketType.name}} with the .ts component in order to work with this value efficiently? Here is a sample of the template code: <mat-option *ngFor="let ticketType of ticketTypes ...

AngularJS blueimp file upload not functioning as expected

I'm currently working on testing the integration of the blueimp jquery-fileupload plugin with angularjs. Here is the simplified code I have written for this purpose: [controller.js] app.controller('myAppController', function ($scope, uplo ...

Tips for managing Typescript Generics while utilizing the styled function provided by the '@mui/material/styles' package

import Table,{TableProps} from 'my/table/path' const StyledTable = styled(Table)({ ...my styles }) const CustomTable = <T, H>(props: TableProps<T, H>) => { return <StyledTable {...props} /> } This is the issue I encoun ...

What is the best way to merge arrays within two objects and combine them together?

I am facing an issue where I have multiple objects with the same properties and want to merge them based on a common key-value pair at the first level. Although I know about using the spread operator like this: const obj3 = {...obj1, ...obj2} The problem ...

Guide to defining AngularJS 1.x Material theme color in SCSS

Is there a way to define Angular 1.x material theme colors as SCSS properties? Specifically, I am looking to use the theme's primary color for the background property. Here is an example: .sampleclass {background: theme-primary-color;} ...

Determine the subtotal for a particular item using AngularJS

Is there a way to apply the sub total amount to a specific item only? Currently, in my stackblitz example, when I add a new item and change the quantity of that last item, all recently added items also get updated. I want to modify the "changeSubtotal()" ...

Unexpected behavior with Angular directives

Looking for a way to achieve two-way binding in AngularJS directives with boolean values? Here's an example of a directive: var xmlToHtml = function () { return { restrict: "A", templateUrl: 'Components/XML2Html/views/XML2Htm ...

Encountering an issue with Jest when using jest.spyOn() and mockReturnValueOnce causing an error

jest --passWithNoTests --silent --noStackTrace --runInBand --watch -c jest-unit-config.js Project repository An error occurred at jest.spyOn(bcrypt, 'hash').mockRejectedValue(new Error('Async error message')) Error TS2345: The argum ...

Trouble with yarn not functioning properly when using a Nexus 3 npm proxy repository

I have configured a Nexus 3 Manager to serve as a host for private npm packages. Within the nexus are three npm repositories: one labeled hosted, another as proxy, and a third named group which combines the former two. The npm bearer realm has been activat ...

The 'Key' identifier is not valid for indexing the 'Object' data type

Currently attempting to incorporate functional pluck with a specific sound type, but encountering an issue: function extract<Object extends {}, Key = keyof Object>(key: Key): (o: Object) => Object[Key] { return object => object[key]; } Erro ...

Is there an alternative method to retrieve model value on controller in Angular bootstrap ngbdatepicker since the (change) method has been removed?

Currently, I am working with ngbdatepicker in Bootstrap. I have added a datepicker selector to appcomponent.html and the datepicker is showing up. Now, I need to retrieve that model value into the controller so that I can pass it to the parent appcomponent ...

Tips for integrating a "datetime" picker in your AngularJS application

Currently working on an AngularJS application. The single page has a date input that needs to be added. Date Input <input type="date" ng-model="InputDate" /> Any suggestions on how to accomplish this task? ...