I am using a GlobalDataService
( referred from here ) to store response data an from login API on a global variable to be used for some other API calls.
login():
if (_token) {
// store username and jwt token in keep 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;
// return true to indicate successful login
return true;
}
Then inside xx.service.ts
file, I'm accessing this global variable like shown below in the constructor()
which is then consumed 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 Problem
After I logout ( during which data in global variable is cleared ) and then login with another user account, the functions in service.ts
is still using previous data stored in those global variable.
inside logout():
this.gd.currentUserData={};
this.gd.currentHospitalData={};
I think the issue is constructor is instantiated only once and hence the new data assigned to global variable in not reflected in .service.ts
file.
How can I fix this issue? or Is there a better approach to handle this situation?
Note: Earlier I used localstorage
to store these data but since it can be modified via Chrome Dev Tools, I am now considering using global variables.
Update
I know this is hacky and not proper way to do, but I notice that calling window.location.reload();
on logout() solves the issue.
Apparently, this issue seems to have resolved. I had to move my Provider declaration for my services from app.module.ts
to a lower level in the app component after which successful login redirects to.
But I'm still looking for a proper solution / approach with login data handling.
The real issue was I had declared Provider for my .service.ts
's inside app.mopdule.ts
. This caused the constructor for those services to instantiate only at first load of the app. So when I logged out and logged in again, the newly assigned data was not reflecting in those .service.ts
files,
I moved Provider declaration for those services to the component that is being redirected to after a successful login. Now after every successful login, the constructor will instantiate and newly assigned value will be relfected in those .service.ts
files.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With