The logout feature might refresh the page, yet the user remains logged in

Currently, I am enrolled in a course on Udemy where the instructor is utilizing Angular 2. My task involves building the app using the latest version of Angular. The issue that I am facing pertains to the logout functionality. After successfully logging out and refreshing the page to display the login form again, I notice that the system briefly shows the login form before reverting back to the logged-in state.

The backend's logout method:

@RequestMapping(value="/loggedOut", method=RequestMethod.POST)
public ResponseEntity logout(){
    SecurityContextHolder.clearContext();
    return new ResponseEntity("Logout Successful!", HttpStatus.OK);
}

The logout function within my login service:

logOut() {
const url = 'http://localhost:8181/loggedOut';
const basicHeader = 'Basic ' + localStorage.getItem('credentials');
const headers = new HttpHeaders({
  'x-auth-token' : JSON.stringify(localStorage.getItem('xAuthToken')),
  'Authorization' : basicHeader
});
return this.http.post(url, '', { headers, responseType: 'text'});

The button responsible for initiating the logout process:

logout() {
  this.loginService.logOut().subscribe(
    res => {
      location.reload();
      console.log("Logged out")
    },
    error => {
      console.log(error)
    }
  );

Essentially, the flow goes as follows: Logged in -> Login form -> Logged in

Snapshot of being logged in: https://i.sstatic.net/AO8Jj.png

Screenshot of the login form: https://i.sstatic.net/rHL4O.png

When removing the reload method, it is evident that the logout method is triggered and receives a 200 response from the backend.

https://i.sstatic.net/J6krZ.png

Network tab status prior to refreshing:

https://i.sstatic.net/LghYO.png

Response received from the server before refreshing:

https://i.sstatic.net/0cVU1.png

Answer ā„–1

To ensure complete data privacy, it is recommended to clear out your localStorage when logging out by using the following code:

localStorage.clear();

This action effectively eliminates any remnants of user activity within the app upon logging out.

Answer ā„–2

**Give This Method a Try **

signOut() {
   this.authService.signOut().subscribe(
    response => {

      if(response) {
        // Clear local storage
        localStorage.clear();
        // Navigate to the login component
        this.router.navigate(['login']);
        console.log("Successfully Logged out")
      }     
    },
    err => console.log(err));
}

No need for page refresh! Note: You can also clear local storage when the login component is loaded in the browser by simply adding localStorage.clear() inside the ngOnInit method of the loginComponent

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

Updating pointers to elements depending on their current status

I am working with an array and looping through it to create div elements. Depending on whether the divs are 'active' (determined by state), I want to assign them the ref property. The ref is also the parameter for a hook that adds an onclick list ...

My changes to the HTML file are not being reflected in the browser, even after clearing the cache. This is happening in an Angular and Node.js application

I'm currently developing an application using Angular and Node.js. I've noticed that when I make changes to the HTML file, the browser isn't updating even after clearing the cache. Could this be a coding issue? Any suggestions on how to fix ...

Angular code for opening a PDF from an API response in a new tab

It's been nearly three days and I could really use some assistance with this issue I'm facing. Inside my Node application, there is an API call that utilizes HTTPS to connect to an external API and retrieve a PDF file. The PDF code snippet looks ...

Implement Javascript Event Listener

I'm a newcomer to the world of javascript and Iā€™m struggling to understand why the code below isn't functioning correctly: var displayMessage = document.getElementById("notification"); displayMessage.addEventListener("click", function() { ...

Tips for displaying only a list of folders in elfinder, a jquery file management plugin

Currently, I am working on enhancing the features of a file manager plugin that allows users to manage their folders effectively. One key functionality of the plugin is the ability for users to share specific folders with others. However, if a folder has n ...

What is the best way to decouple the data layer from Next.js API routes?

Currently, I am working on a project using Next.js with MongoDB. My setup involves using the MongoDB client directly in TypeScript. However, I have started thinking about the possibility of switching to a different database in the future and how that would ...

Cookies with the HttpOnly attribute are not transmitted in a request

I have implemented the use of HttpOnly cookies in my Java code like this: ... Cookie accessTokenCookie = new Cookie("token", userToken); accessTokenCookie.setHttpOnly(true); accessTokenCookie.setSecure(true); accessTokenCookie.setPath("/"); response.addC ...

JS Equal Heights is a JavaScript plugin designed to ensure

Good evening, A while back, I implemented a JavaScript code snippet to create equal height columns on my website. The initial script looked like this: <script type="text/javascript"> var maxHeight = 0; $(".level").each(function(){ maxHe ...

Is the renderer.setSize in Three.js calculated as a percentage of the screen size?

Is it possible to calculate the renderer.setSize based on a percentage of the screen? For instance, could I set my frame to be 80% of the device width and 80% of the device height? ...

Identifying a change in the source location of an iframe element

I am working with an iframe object that is currently set to a specific page's URL. Here is an example: <iframe src="http://en.wikipedia.org/wiki/Special:Random"></iframe> My goal is to display an alert whenever the location of the iframe ...

Encountered Runtime Error: TypeError - Carousel triggering issue with reading properties of null (specifically 'classList') in Tailwind Elements

Currently, I am encountering the error message: Unhandled Runtime Error TypeError: Cannot read properties of null (reading 'classList') while utilizing the Carousel component. The problem arises when I attempt to populate the carousel with images ...

Using Cypress fixtures with TypeScript

After transitioning from using Cypress with Javascript specs to Typescript, I encountered a challenge in working with Fixtures. In Javascript, the approach below worked; however, I faced difficulties when switching to Typescript. Fixture JSON file: I sto ...

Exploring Iconography in Amcharts

Is there a simple way to include images/icons within a chart using x and y coordinates? I'm new to javascript and amcharts (am4charts) so any assistance would be greatly appreciated! I've searched for solutions on stackoverflow, like this one o ...

Ensuring the presence of Objects/Functions in different browsers using javascript

I am seeking advice on the best practices for testing object existence for cross-browser compatibility. There are numerous methods available for testing whether an object/function/attribute exists. While I could utilize jQuery or another library, my prefe ...

Using Selenium and Python to showcase the source of an image within an iframe

My goal is to automatically download an image from shapeNet using Python and selenium. I have made progress, but I am stuck on the final step. from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.s ...

How to Dynamically Set AngularJS Filter (like date or currency) Using Variables

When working with Angular, it's possible to easily apply filters to format variables, like so: {{ myDate | date }} {{ myMoney | currency }} But, is there a way to dynamically set the filter type in a more flexible manner as shown below? // controll ...

tips for concealing a row in the mui data grid

I am working on a data grid using MUI and I have a specific requirement to hide certain rows based on a condition in one of the columns. The issue is that while there are props available for hiding columns, such as hide there doesn't seem to be an eq ...

Is there a way for me to showcase something in the console after clicking on an event in fullcalendar?

In the configuration: select: this.handleManualSelect.bind(this), dateClick: this.dateClick.bind(this), eventClick: info => { console.log(info, 'click'); }, eventMouseEnter: info => { console.log(inf ...

Determining whether a string includes any elements from an array

Recently, I've embarked on a journey to learn javascript and ventured into developing a small chrome extension. This extension aims to scan item listings on a specific website for products that match keywords provided by users. I am seeking guidance o ...

Tips for effectively displaying the current list of tasks in a practical manner

Looking for suggestions on how to add a task switch button (device hardware button) functionality in my application. Does anyone have any creative ideas on how to display the task list in a more practical way? Note: I am aware of the function that ret ...