Clearing data initialized in a service constructor upon user logout in Angular

In my current setup, I am utilizing a GlobalDataService, which I discovered from this post on Stack Overflow ( source here ), to store response data from a login API in a global variable. This data is then used for subsequent API calls.

login():

 if (_token) {

    // Storing the username and JWT token to keep the user logged in between page refreshes
    console.log(this.gd.currentUserData)
    this.gd.currentUserData['userID']=_id;
    this.gd.currentUserData['username']=username;
    this.gd.currentUserData['token']=_token;
    // Returning true to indicate successful login
    return true;
}

Within the xx.service.ts file, I access this global variable in the constructor() as shown below. This data is then utilized by various functions to make API calls.

constructor(private http: Http,  private gd: GlobalDataService) {

    let currentUser = this.gd.currentUserData;

     this.token = currentUser && currentUser.token;
     this.userID=currentUser.userID;

}

The Issue

Upon logging out (which clears the data in the global variable) and subsequently logging back in with a different user account, the functions in service.ts still retain the previous data stored in the global variables.

Inside logout():

this.gd.currentUserData={};
this.gd.currentHospitalData={};

I suspect that the problem lies in the constructor being instantiated only once, thus not reflecting the new data assigned to the global variable in the .service.ts file.

How can I resolve this issue? Is there a better approach to handling this situation?

Note: Previously, I relied on using localstorage to store this data, but due to its vulnerability to modification via Chrome Dev Tools, I have transitioned to using global variables.

Update

Although it may not be the most elegant solution, I found that calling window.location.reload(); in the logout() function resolves the issue.

It seems that the issue has been resolved. I had to adjust the Provider declaration for my services from app.module.ts to a lower level in the app component where successful logins redirect to.

However, I am still open to exploring better solutions or approaches for handling login data efficiently.

Answer №1

The main issue stemmed from declaring the Provider for my .service.ts files within the app.module.ts. As a result, the constructor for these services would only be instantiated upon the initial app load. This led to the problem of not seeing the updated data when logging out and back in.

To resolve this, I relocated the Provider declaration for these services to the component that is accessed after a successful login. Now, with each successful login, the constructor will be triggered, ensuring that any newly assigned values are accurately reflected in the .service.ts files.

Answer №2

Modifying "global variables" through Chrome dev tools is possible, but can be challenging.

If your data isn't sensitive, you have the flexibility to store it wherever and however you prefer without concerns.

Your challenge arises from the fact that the constructor is only initiated once due to services being singletons, maintaining a single instance throughout the session.

To address this, there are a few solutions available:

  • Utilize local storage / session storage
  • Create a method to perform the tasks of the constructor and execute it during login
  • Develop a service dedicated solely to logging in users, utilizing it for each login/logout process

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

Angular 2: Another service is unable to find the custom service

I have a situation where I am using an HttpInterceptor and trying to integrate a NotificationService within it. However, I encountered an issue where the NotificationService appears to be undefined in the httpInterceptor. Is there something that I missed o ...

The custom loader for Webpack (haml-haml-loader) appears to be malfunctioning

I am fairly new to managing my own Angular applications. I found this helpful guide for setting up haml loading through webpack. However, the guide is quite outdated and ngx no longer supports eject, so I am experimenting with this package to customize web ...

Determine the data type of a variable in TypeScript by utilizing the compiler API

I am facing an issue with retrieving the type of a variable using the compiler API. Here is some background information on my situation: Since I execute everything in memory, I have had to create my own compiler host. This is necessary because the typechec ...

By default, all groups in the Kendo UI Angular 2 Grid are collapsed

Just started using the new Kendo UI for Angular 2 Grid and I have a question - is it possible to collapse all groups by default when grouping data? I noticed there is a method called collapseGroup(), but it's unclear how to use it or if there's ...

Angular 2 now has the ability to detect keydown events triggered from any part of the page

Is there a way to enable keyboard control for a view? I attempted using document.keydown, but it wasn't successful. How can I make the document accept keyboard input? A solution that worked for me was implementing this in my component class: @HostLi ...

Node.js is having trouble retrieving information from the SQLite database

Here's a simple code snippet I'm using to retrieve data from my sqlite database. Index.ts: import { Database } from './Class/database'; Database.checkIfExists("some ID"); Database.ts: export class Database { static sqli ...

Utilizing a custom function declared within the component to handle changes in Angular's ngOnChanges

Although it may seem like a simple question, I'm struggling to find a solution. Here's the issue at hand: In my Angular Component, there's a function that I need help with. export class RolesListComponent implements OnInit, OnChanges { ...

The concept of Typescript involves taking a particular type and generating a union type within a generic interface

Picture a straightforward CollectionStore that contains methods for creating and updating a record. The create() method takes in a set of attributes and returns the same set with an added id property. On the other hand, the update method requires the set t ...

Angular ngx-translate: Responding to language change event

Is it possible to detect the change in the "current language" using the ngx-translate library? Which JavaScript event should I use to accomplish this task? To clarify, please refer to this straightforward example: https://stackblitz.com/edit/github-yvbmgu ...

Troubleshooting Authentication Issues with .NET Core and Angular 2/4

I have been following a tutorial on this particular website to implement .NET Core API authentication for Angular 2/4. The registration process works smoothly, however, I am encountering an issue with the token during authentication (login). The server is ...

Ways to overlook compilation errors in Typescript/Electron for unreached code

I am diving into Typescript/Electron and attempting to create a text-based game. My journey began with a basic Electron application and I started implementing core logic using classes/interfaces that reference classes I have yet to implement. The snippet o ...

Typescript and React: Unraveling the intricacies of complex

Is it possible to define custom types verified by a function in Typescript/React? Instead of using a simple 'string' type, I envision using a regex expression: interface Verify { email: /.+@.*\.com/g; } The specific regex above might not ...

Error with Angular InjectionToken utilization

We are encountering an issue while trying to inject a value using InjectionToken. The error message that we are receiving is as follows: ERROR in Error encountered resolving symbol values statically. Only initialized variables and constants ...

Ionic Data Storage Solution

Question: How can I assign the value "dogovor" from "session_storage" to the variable "ttt"? ttt: any = this.storage.get('session_storage', 'dogovor'); It seems that the above code sample is not functioning as expected. Thank you! ...

Angular - Automatically update array list once a new object is added

Currently, I'm exploring ways to automatically update the ngFor list when a new object is added to the array. Here's what I have so far: component.html export class HomePage implements OnInit { collections: Collection[]; public show = t ...

Error-throwing constructor unit test

In my code, I have implemented a constructor that takes in a configuration object. Within this constructor, I perform validations on the object. If the validation fails, I aim to throw an error that clearly describes the issue to the user. Now, I am wonde ...

Is there an alternative course of action since determining if Observable is empty is not feasible?

I am diving into Angular 11 and exploring the world of Observables and Subjects as a beginner. Within my application, I have a mat-autocomplete component that organizes its results into categories. One of these categories is dedicated to articles, and I&a ...

Adjusting the size of the Knob in Ionic 5 upon pressing it

Is there a way to change the size of the knob in an "ion-range" element when it is pressed? I have checked the documentation, but could not find any information in the "ion-range" section. I would like to make this adjustment in SCSS: Normal Behavior htt ...

Global Declaration of Third-Party Modules for Seamless Use without Imports in Webpack5 with TypeScript

Within my React project utilizing Webpack, I have opted to declare certain modules as global entities to eliminate the need for importing them every time they are needed. In my Webpack configuration file: plugins: [ new webpack.ProvidePlugin({ ...

Using the hash(#) symbol in Vue 3 for routing

Even though I am using createWebHistory, my URL still contains a hash symbol like localhost/#/projects. Am I overlooking something in my code? How can I get rid of the # symbol? router const routes: Array<RouteRecordRaw> = [ { path: " ...