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.