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

Ways to verify if an item is an Express object?

Currently, I am utilizing typescript to verify whether an app returned by the Express() function is indeed an instance of Express. This is how I am attempting to accomplish this: import Express from "express" const app = Express() console.log( ...

Add flexible templates into List element in Ionic version 3

My Progress Being a newcomer to ionic, I successfully created a List component in ionic 3 that retrieves JSON data from the server and displays it as a list layout on specified pages using a list selector. Objective I am looking to showcase various list ...

Frontend Will Not Be Able to Access Cloud Run Environment Variables when in Production

My current setup involves using docker to build an image through Google Cloud Build and Google Cloud Registry. I have Pub/Sub triggers in place to populate Cloud Run instances with new Docker images upon a successful build. The issue I am facing is that m ...

What is the best way to establish communication between the browser and an express.js server while utilizing angular ssr?

I've encountered a server-side rendering (SSR) issue that does not seem to be addressed in either the Angular documentation or the new Angular developer documentation. My inquiry pertains to transferring data from the browser to the server, as oppose ...

Steps to implement Angular routerLink on an image for seamless navigation to a different component

Is there a way to create an interactive image that leads to other sections within Angular? The intention is for this particular image to serve as a miniature profile picture of the existing user, located in the navigation bar. <img ngSrc="{{User.photo ...

Angular 6 Observer - Double Authentication Triggered

I am currently learning about Observer and Http requests. My code is functioning properly, but it lacks elegance and the issue I am facing is that the URL is being called twice. isAuthenticated() { let obs = this.http.get('http://localhost:8080/a ...

Here's a new take on the topic: "Implementing image change functionality for a specific div in Angular 8 using data from a loop"

I need to create a list with dynamic data using a loop. When I click on any item in the list, I want the image associated with that item to change to a second image (dummyimage.com/300.png/09f/fff) to indicate it's active. This change should persist e ...

Exploring the connections among Angular, Angular-CLI, Angular-seed, and Ionic

I'm currently tackling a project in Angular 2. I'm a bit puzzled about the relationship between CLI, Seed, and Ionic with Angular. Are they considered sub-frameworks of Angular? ...

Ways to implement useState in a TypeScript environment

Hello, I am currently using TypeScript in React and trying to utilize the useState hook, but encountering an error. Here is my code: import React , { useState } from "react"; interface UserData { name: string; } export default function AtbComponent( ...

Preventing a page refresh in Angular 2 on an ASPX page: Strategies for success

The use of the pagemethod is successful, but I encountered an issue with the webmethod causing the page to refresh, which defeats the purpose of using Angular 2. Is there a way to prevent the form from refreshing the page? index.aspx <body> &l ...

Issue in TypeScript: Property '0' is not found in the type

I have the following interface set up: export interface Details { Name: [{ First: string; Last: string; }]; } Within my code, I am using an observable configuration variable: Configuration: KnockoutObservable<Details> = ko.observable& ...

Strategies for transferring ngModel data from child components to parent components (child to parent to grandparent)

I am currently working on multiple parent components that utilize template-driven forms: user-data.components.ts admin-data.components.ts customer-data.components.ts Each of these parent components have form elements that are child components utilizing NG ...

What is the best way to associate a select dropdown with a form in Angular 2 using formBuilder

After conducting some research, I was surprised to find that the process is not as straightforward as I had expected. I have come across various methods using ngModel, such as Bind and fetch dropdown list value in typescript and Angular2, among others. Ho ...

Error: The absence of an element identified by the locator does not cause the protractor spec to fail, but rather it executes successfully

This automation framework follows the page object model and utilizes the async/await approach rather than promises. TypeScript is used, with compilation to JavaScript (protractor) for script execution. Page Object: async addProjectDetails(): Promise< ...

Uh oh! An issue occurred: Cannot access values of an undefined property (reading 'valueOf')

I am attempting to loop through the JSON data and extract the start time and end time keys. I have tried two different methods in my API code to achieve this. The console.log is not showing any errors, but the other loop method is causing an error to appea ...

Try out NextJS API middleware by running tests with Jest

I have a middleware setup in my NextJS API route, located at /src/middleware/validateData/index.ts. It's used to validate request data using a schema. import { NextApiRequest, NextApiResponse } from 'next'; import schema from './schema ...

Loading a large quantity of items into state in React Context using Typescript

I am currently working on a React context where I need to bulk load items into the state rather than loading one item at a time using a reducer. The issue lies in the Provider initialization section of the code, specifically in handling the api fetch call ...

React Typescript - Unexpected character ',' encountered at line 1005

Currently, I am utilizing Typescript within a React application that integrates with Graphql. Encountering an error: ',' expected.ts(1005) After researching possible solutions, most suggest that the issue might be due to using an outdated ve ...

Encountering the error message "Undefined. Please implement using the following snippet" while running a protractor cucumber typescript feature file

Currently, I am utilizing Protractor with TypeScript and Cucumber for automation purposes. After going through some informative articles, I have successfully incorporated feature files and step definitions into my end-to-end project. Below is the structur ...

Retrieve information from various MongoDB collections

Greetings! I currently have a database with the following collections: db={ "category": [ { "_id": 1, "item": "Cat A", }, { "_id": 2, "item": "Cat B" ...