Tips for preserving the values of a variable after refreshing the page

I've encountered an issue with my canActivate method. After signing in on my website, I set a boolean variable to true. However, when I refresh the page, the value resets back to false. It is crucial for me to maintain this value even after a page refresh.

Here are the relevant codes:

export class AuthService{
   loggedin = false;

   isAuthenticated(){
     return this.loggedin;
   }

   login(){
     this.loggedin = true;
   }

   logout(){
     this.loggedin = false;
   }
}

and the canActivate method:

@Injectable()
export class AuthGuard implements CanActivate{

   constructor(private authService: AuthService, private router: Router){}

   canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean{
     if(this.authService.isAuthenticated()){
       return true;
     }else{
       this.router.navigate(['/']);
     }
   }
}

After logging in, I call the login function to set the value to true. Unfortunately, upon reloading the page, the value reverts back to false. The only way I found to change this value is by calling the logout method. Can you help me understand why this happens and how can I fix it?

Answer №1

Utilize the power of localStorage with these revamped methods that should function seamlessly:

   isUserAuthenticated(){
     return localStorage.getItem('loggedin', true);
   }

   userLogin(){
     localStorage.setItem('loggedin', true);
   }

   userLogout(){
     localStorage.removeItem('loggedin'); // you can either delete the item or set it to false like this: localStorage.setItem('loggedin', false);
   }

With these changes, your application will now check if the user is authenticated each time you refresh.

Answer №2

When utilizing localStorage.setItem(), a bug may persist where even after restarting the browser, the variable remains intact—potentially exposing sensitive user login information, which is not ideal. A more secure approach would be to utilize window.sessionStorage["xxx"], as this confines the variable's validity to a single session. If the browser is restarted, the variable automatically becomes invalid, aligning with common security practices.

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 exploring the ins and outs of implementing nested child routing

Within my app-routing.module.ts file, I define the loading of child components like so: { path: 'account', loadChildren: () => import('./components/account/account.module').then((esm) => esm.AccountModule) }, Followin ...

Exploring the world of Angular data services enhanced by RxJS

I am currently developing an Angular application that interacts with a REST-like backend system. The user interface features a master/detail layout, where users can select an element on the left side to view its details on the right. I am implementing thi ...

Issues with form validators failing to work properly in Angular 2

I'm currently working on an Angular 2 form that utilizes form validators using the form builder module. After entering data in a text box, it successfully passes validation (indicated by a green outline around the div). However, upon loading the for ...

Obtaining a collection of distinct values from an observable stream or pipeline

I'm stuck on figuring out how to filter for distinct values while filtering within a .pipe() <mat-form-field class="filterField"> <input formControlName="filterParam2" matInput placeholder="Filter& ...

Node was experiencing difficulty locating a module alias that had been defined in the tsconfig file and package.json

I'm currently working on deploying a typescript project in production mode. You can find the code on Github here Executing npm run start:dev launches the server at http://localhost:3000/ Running npm run build generates the dist folder The definitio ...

Issues arise when dynamically generated <input> elements are not displaying on the webpage

I am facing an issue with rendering a form dynamically using a string in my Angular application. Upon clicking the "Add Step" button, the template string is supposed to be added to a list and displayed using ngFor directive. However, I am only seeing the ...

Combining a JSON object with a dropdown menu within an Ionic 3 Angular 4 application

I've hit a roadblock while attempting to integrate a JSON response into an ion-option tag in my HTML code: <ion-item> <ion-label>Country</ion-label> <ion-select formControlName="country"> ...

Unable to transform data into ng2-chart [Bar Chart]

Exploring angular for the first time and currently working with Angular 7. I am in need of converting my api data into the ng2-charts format. This is a snippet of my api data: { "status": 200, "message": "Fetched Successfully", "data": [ ...

While the router Link successfully generates the correct URL, it is failing to redirect to the component and display the data as intended

While working on my angular 7 app, I encountered an issue when navigating to the component report details. When using router link, it only creates a URL in the browser but does not actually redirect until I click Enter. The routing works correctly only i ...

What are the best practices for incorporating state in a TypeScript React file with only a default function?

I recently started a new React Native project by initializing tabs using TypeScript. There are 2 tabs in this example, with each tab's content being in a .tsx file that only contains a single line of code: export default function. I'm wondering h ...

React modal not closing when clicking outside the modal in Bootstrap

I recently utilized a react-bootstrap modal to display notifications in my React project. While the modal functions correctly, I encountered an issue where it would not close when clicking outside of the modal. Here is the code for the modal: import Reac ...

How to dynamically incorporate methods into a TypeScript class

I'm currently attempting to dynamically inject a method into an external class in TypeScript, but I'm encountering the following error. Error TS2339: Property 'modifyLogger' does not exist on type 'extclass'. Here's the ...

What is the interaction between a service worker and a sub-domain?

I have been exploring how Angular 6 works with ngsw-config.json for service worker configuration, but I'm unsure about its interaction with sub-domains. Based on my current understanding: When a user visits example.com, The service worker is regist ...

Enabling the "allowUnreachableCode" Compiler Option in Visual Studio 2015 Triggers "JsErrorScriptException (0x3001)" Issue

We've implemented TypeScript in our Visual Studio 2015 (Update 2) setup for a non-ASP.Net project consisting of pure HTML and JavaScript. In order to disable the 'allowUnreachableCode' option, we made adjustments in the tsconfig file. It&apo ...

Setting a default value in a formControl - a guide

I've been attempting to establish a default time value in an input field, but I found that the "value" attribute didn't work for me. <input class="form-control" name="absolute type="time" value="23:59" formCo ...

Sending a post request to an Express.js API from a different device

I currently have a server running on localhost:3000, with my app.js set up to utilize the angular router. When attempting to access localhost:3000 in my browser (for example: app.use('/', express.static(path.join(__dirname, '/dist/Client&apo ...

What is the process for searching my database and retrieving all user records?

I've been working on testing an API that is supposed to return all user documents from my Mongo DB. However, I keep running into the issue of receiving an empty result every time I test it. I've been struggling to pinpoint where exactly in my cod ...

Enhance the design of MDX in Next.js with a personalized layout

For my Next.js website, I aim to incorporate MDX and TypeScript-React pages. The goal is to have MDX pages automatically rendered with a default layout (such as applied styles, headers, footers) for ease of use by non-technical users when adding new pages. ...

Refresh the webpage when using the browser's back or forward button in AngularJS with ui-router

In my AngularJS app, I have configured the ui-router state as follows: $locationProvider.html5Mode(true); $stateProvider .state('index', { url: '/index?zoom&center', views: { ...

Is there a way to insert a secured page right before accessing the dashboard?

I am trying to create a locked page that will display a message when users access the web app from a mobile device and load a mobile layout page displaying a message like mobile is not supported. I was considering using document.addEventListener('DOMC ...