In the Angular/Typescript how I declare a global variable to control login status. When I logged in, the global variable going to the true state, and when I log out how that changes to a false state.
-
1https://stackoverflow.com/questions/38906359/create-a-global-variable-in-typescript https://stackoverflow.com/questions/55007402/declaring-a-global-variable-in-angular-6-typescript – pullidea-dev Jun 01 '21 at 01:45
-
3There is nothing called a global variable in Angular. The best you can do is use a service to handle all the data and logic for user sessions. You can define the variable in the service which will be globally accessible. But keep in mind, if the user refreshes the browser your variable will be empty so you can use local storage for the same if you don't want to lose the data on page refresh. – BlackList96 Jun 01 '21 at 02:15
-
Thank you! I got it. I have to do like this – Nirodha Wickramarathna Jun 01 '21 at 02:26
1 Answers
I don't want it to sound as a snide question, but what do you mean when I log in? Since login happens against some server-based authentication provider, there is no built-in definition of "login" in Angular.
Let's say you get a JWT token from the server when you supply login and password. That allows you to submit this token in subsequent requests and not get asked ("challenged") for login/password again.
In this case JWT has a number of claims (for example, exp that stands for expiration) that gives a natural "global" variable to check whether user is logged in - and also whether their login hasn't timed out yet.
There are other ways to authenticate. Legacy was is cookie. So, you can read the cookie, and maybe even get some meaning out of it. But the presence of the cookie doesn't automatically mean that the user is logged in, until the cookie is processed on the server.
So, in summary - JWT provides you both better authentication mechanism and easier way to verify that the user is logged in
Happy coding
- 9,248
- 10
- 57
- 89