Storing Data Locally in Angular with User Authentication

Using angular8, I encountered an issue where logging in with USER1 credentials, closing the browser, and then attempting to log in with USER2 credentials still logged me in as USER1. While adding code to the app component resolved this problem, I faced an issue with local storage being cleared upon refreshing the browser, which was not ideal. How can I address this situation?

import { Component, HostListener } from "@angular/core";

@Component({ selector: 'app-root', templateUrl:"./app/app.component.html" }) 
export class AppComponent  { 
    @HostListener("window:onbeforeunload",["$event"]) 
    clearLocalStorage(event) { 
    localStorage.clear(); 
    }
}

The solution involves storing user details and jwt token in local storage in order to maintain user login status between page refreshes.

login(email, password) {
    return this.http.post<any>(`${Constant.apiUrl}account/login`, { email, password })
        .pipe(map(user => {
            localStorage.setItem('currentUser', JSON.stringify(user));
            this.currentUserSubject.next(user);
            return user;
        }));    
}

Answer №1

@HostListener("window:onbeforeunload",["$event"]) 

When the tab is closing, this event is triggered. It may be better not to attach this event and instead consider using a logout button, timeout feature, or a combination of both.

Token invalidation should ideally be handled by the server (e.g. through expiration) or by the user (by logging out). This aligns well with the standard OAuth 2.0 protocol.

Answer №2

In my opinion, the most effective approach is to decouple the clearing of localStorage from the @HostListener("window:onbeforeunload",["$event"]) event. The reason why localStorage values are cleared when you refresh the page is because this event is triggered before the page is reloaded. This explains why your localStorage data is wiped out during a page refresh.

As suggested by @NotMyDay, alternatives include implementing a logout button or setting a timeout for token expiry on the server side, which is what I am currently doing.

Another consideration is handling scenarios where a user accidentally closes the window/tab with their credentials still active. In such cases, redirecting the user to the main page instead of the login page would be more user-friendly.

If automatic logout upon closing the browser is necessary to prevent unauthorized access on shared computers, using sessionStorage may be a better option. Reliable window event handlers for detecting window close events are limited, although techniques like checking for page refreshes (!router.navigated) or capturing keypress events (e.keyCode == 116 for F5) have been explored.

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

How do I access the current state in Ngrx Store without the need to subscribe, specifically for use in a route Resolve?

Presently, my Resolve implementation is quite straightforward: export class UserResolve implements Resolve<any>{ constructor(private userService: UserService){} resolve(route: ActivatedRouteSnapshot){ return this.userService.get(route. ...

What is the correct way to specify an image path for a background URL?

Currently, I am setting a background image for the hr tag using the following code: <hr style="height:6px;background: url(http://ibrahimjabbari.com/english/images/hr-11.png) repeat-x 0 0;border: 0;margin:0px!important"> However, I have now saved th ...

Issue encountered after updating to Spartacus 3.0 from 2.0: Unable to access the 'findStores' property due to a TypeError

After upgrading to Spartacus 3.0 from 2.0, everything seems to be working fine except for this particular error that keeps popping up. I followed the steps provided by SAP team on the documentation site to add the storefinder module. Error in spartacus-co ...

Only apply patches to untouched values

Looking for a way to patch only the pristine properties of my reactive form in Angular. Received updates from a websocket service regarding user data, and want to update the form based on the payload without changing dirty properties. Below is the code s ...

Utilizing the variables defined in the create function within the update function of Phaser 3

I'm facing an issue in my game where I can't access a variable that I declared in the create function when trying to use it in the update function. Here is a snippet of what I'm trying to achieve: create() { const map = this.make. ...

Creating an extended class with mandatory properties

In order to streamline code sharing between two classes that overlap, I decided to create a new class called Common. For one of the subclasses, I needed all the properties from the Common class to be required. My initial thought was to utilize the Require ...

Guide to sending a text from HTML to an Angular 8 Component through the use of the (click) function

After successfully implementing this code: <a [routerLink]="['/menuItemOne']"> <span [innerHTML]="(mystrings$ | async)?.menuItemOne | htmlToText"></span> </a> I now face the challenge of updating t ...

Display a unique element depending on the path of the Dynamic Angular Routing

Here are the routes I am working with: /dashboard /dashboard/view-all /dashboard/edit/:id One specific issue I've encountered is related to showing/hiding the EditComponent based on the dynamic router. Typically, I can show/hide Angular components ...

Ways to resolve the issue: ""@angular/fire"' does not contain the exported member 'AngularFireModule'.ts(2305) in an ionic, firebase, and

I am facing an issue while attempting to establish a connection between my app and a firebase database. The problem arises as I receive 4 error messages in the app.module.ts file: '"@angular/fire"' has no exported member 'AngularFi ...

Angular automatically protects routes by default

In the application I've created, there is a requirement for most routes to be protected and accessible only when logged in. Is it feasible to implement a default route guard while also specifying certain routes that should remain open? ...

Typescript validation of tokens using Azure functions

Currently working on a website utilizing Azure Static Web App, where the login/registration is managed by Azure B2C. The backend API consists of typescript Azure functions integrated with Azure Static web app. Certain API calls can only be accessed when th ...

"Unlocking Angular event intellisense in Visual Studio Code: A Step-by-Step Guide

Currently, I am enrolled in an Angular course on Udemy. The instructor prefers using VS Code as his code editor, and one interesting feature he showcased was when he tried to add events to a button element. As soon as he opened the parenthesis after the bu ...

What's the best way to assign a dual-value condition within a form group field?

// Setting up a form group in Angular this.form = this.fb.group({ id:[], name: [ details.name || '' ] }) I am wondering if it is possible to assign a value in the form based on the content of details.name. If details.name has ...

I am looking to update the color based on the prop value in React

Currently using react along with typescript. My objective is to adjust the color based on the value passed through props. The props will contain either "primary," "secondary," or "brand" as a string type. When the value "primary" is provided, I aim ...

Encountered Error: Rendered an excessive number of hooks beyond the previous render in the framework of Typescript and

I am currently working on integrating Typescript and Context API in an application. Specifically, I am focusing on setting up the Context API for handling login functionality. However, I encountered the following error message: Error: Rendered more hooks ...

Angular Form Container

I am in the process of creating a wrapper for forms. Everything is functioning except for the validation aspect. The issue lies in the fact that my ngForm property does not include the controls from the ng-content. My objective is to have the ngSubmit Even ...

Unfortunately, the package "error-ex" could not be found when attempting to access it through the npm registry

I am encountering an issue while trying to install npm package dependencies in my Angular application. The error message I receive is related to "error-ex@^1.2.0". Can anyone provide guidance on how to resolve this problem? npm ERR! code E404 npm ERR! 404 ...

What is the procedure for transferring the inputted data from an HTML file to its corresponding TS file and subsequently to a different component file?

I have created two components, a login and a home-page. I am attempting to capture user input from the login template, pass it to the login component, and then display it on the home-page template using the home-page component. What is the best approach to ...

Typescript Angular filters stop functioning properly post minification

I developed an angular filter using TypeScript that was functioning properly until I decided to minify the source code. Below is the original filter: module App.Test { export interface IGroupingFilter extends ng.IFilterService { (name:"group ...

Having trouble retrieving a dynamic name with Formcontrol error?

I keep encountering a typeError in this section of code <p *ngIf="formValue.controls['{{obj.name}}'].invalid, but when I manually enter it like this *ngIf="formValue.controls['uname'].invalid it works perfectly fine. What ...