Setting up an Angular 2 session service prior to the activation of a guard

Currently, I have implemented a guard in my app to secure certain routes. The guard relies on a session service to extract credentials from localStorage during NgOnInit. The goal is for the guard to check with the session service for valid credentials before allowing access to protected routes.

import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';
import { SessionService } from './../session/session.service'
 
@Injectable()
export class AuthGuard implements CanActivate {
 
    constructor(
    private router: Router,
    private sessionService: SessionService
    ) { }
 
    canActivate() {
        // Ensure user data is loaded
        //this.sessionService.loadUser();
        if (this.sessionService.isValidSession()) {
            return true;
        }
 
        // Redirect to login page if not logged in
        this.router.navigate(['/login']);
        return false;
    }
}

Here is a snippet of my session service:

export class SessionService implements OnInit {
 .
 .
 .
constructor(
    private authService: AuthenticationService,
) {
    this.timeout = null;
}

ngOnInit() {
    this.loadUser();
}

The issue I'm facing is that the ngOnInit method in the session service does not execute automatically. Instead, I have to manually call loadUser() within the guard. How can I ensure that the ngOnInit of the session service runs before the canActivate method of the guard?

Thank you for any suggestions or solutions!

Answer №1

Avoid using "OnInit" specifically for services; it is better suited for components. Instead, implement the necessary loading logic within the constructor of the service.

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

What could be the reason for the base64 returned by url-loader in webpack appearing to be

After downloading and including the url-loader for Webpack, my configuration looks like this: loaders: [ { test: /.jsx?$/, include: path.join(__dirname, './public/scripts'), loader: 'babel-loader', exclude: /node_modul ...

Implementing a change event upon setting a value to an input element using JavaScript

My plan is to develop a Chrome extension that can automatically fill passwords. The code for this functionality looks like the following: //get the account document.querySelector("input[type=text]").addEventListener('input', () => { ...

Lambda function failing to execute Auth0 methods through the Auth0 node-auth0 SDK

I am working with a lambda function that triggers when a message is added to the SQS queue. Within the message, there is a userId that I want to connect to using the Auth0 node SDK. The code snippet for my GetUserDetails function below shows that it logs ...

Guide on utilizing tslint in conjunction with npx

I currently have tslint and typescript set up locally on my project. In order to run tslint against the files, I am using the following command: npx tslint -c tsconfig.json 'src/**/*.ts?(x)' However, when I run this command, it seems to have no ...

What is the best way to transform this JSON data into an array of key-value pairs in JavaScript?

Dealing with nested JSON data can be challenging, especially when trying to extract key-value pairs efficiently. If anyone has suggestions on how to simplify this process and improve readability, please share your insights. The goal is to transform the ne ...

The useEffect function is failing to execute, leading to an issue with an undefined variable

Attempting to retrieve a specific string with the help of useRouter, then utilizing that same string to access a particular document from Firebase is my current goal. This sequence of actions is supposed to take place within the confines of the useEffect f ...

You are unable to call a function that doesn't have a proper call signature when dynamically defined, yet surprisingly it still functions as intended

Being new to TypeScript, I'm still learning the ropes, so please bear with me if I make mistakes in using this technology! The challenge I'm grappling with involves creating a flexible way to structure my application errors while allowing users ...

What is the best way to send button ids from an array of buttons to a PHP file?

I am looking to generate multiple buttons using just one button and then be able to click on each of them to send their unique id numbers to a PHP file. Below is the code I have: <script> var count=1; document.getElementById("btn").onclick=func ...

Refreshing ng-model within a radio input

Currently, I am utilizing a jQuery library for radio/checkbox components. Although I am aware that combining jQuery with Angular is not ideal, the decision to use this particular library was out of my control and cannot be altered. One issue I have encount ...

Exclude cascading classes in CSS

Help Needed with HTML Lists! <li>A.</li> <li><a href="#">B.</a></li> <li><a class=tr href="#">C.</a></li> <li class=tr>D.</li> <li class=notr>E.</li> I am trying to selec ...

Using Unique Typeface in Ionic Framework 3

I am currently utilizing Ionic3: Your device information: Cordova CLI: 6.4.0 Ionic Framework Version: 3.0.1 Ionic CLI Version: 2.1.18 Ionic App Lib Version: 2.1.9 Ionic App Scripts Version: 1.3.0 ios-deploy version: Not installed ios-sim version: Not in ...

Is there a method to directly download large files from the server without having to wait for the blob response?

I'm currently working on video file requests using axios. I have set the requests with responseType: blob to create a video player once the response is received with window.URL.createObjectUrl(). However, I also have a button that allows the user to d ...

Ways to limit the type based on the value of the argument

Is it possible to narrow down the type of the library in the demo code provided? Can we use the factory function to create a new function fnP with an exact type instead of any? const libOne = { p: () => 0, q: () => 1, }; const libTwo = { x: ( ...

Integrate a service component into another service component by utilizing module exports

After diving into the nestjs docs and exploring hierarchical injection, I found myself struggling to properly implement it within my project. Currently, I have two crucial modules at play. AuthModule is responsible for importing the UserModule, which conta ...

What is the best way to configure dependencies for a production deployment when utilizing Babel within the build script?

From what I understand, Babel is typically used for compiling code, which is why it usually resides in devDependencies. However, if I incorporate the Babel command into my build script and want to run npm install --only=prod before running npm run build d ...

Having trouble with SCSS styles not being applied after refactoring to SCSS modules?

Currently, I am in the process of restructuring an application to ensure that component styles are separated from global styles using CSS modules. However, I have come across an issue where the styles are not being applied correctly. The original code sni ...

The Autofocus feature in HTML5 is malfunctioning in Internet Explorer 9

I am currently working on a project for IE9, and I am having trouble with the HTML5 autofocus keyword not functioning as expected. Specifically, the autofocus feature that puts the cursor in the specified input field is not working in IE9 (and I am forced ...

Utilizing JavaScript to direct website traffic within a set timeframe

I need assistance with redirecting my website on specific days each year. To be more clear, I want to redirect my site from version A to version B between March 1st and April 15th. Unfortunately, I haven't been able to find a seamless solution that d ...

What techniques can be employed to create a fully operational web application using AngularJS?

I have taken on the challenge of understanding AngularJS by creating a webapp. Within my Eclipse environment, I am working with 4 files: main.js, index.html, view1.js, and view2.html. Currently, I can get index.html to load when Tomcat is running. Embedd ...

The style in App.js was rejected and the script was not executed as intended

element, I have encountered a common issue that many others seem to face. The typical solution involves correcting a line of code like this one: app.use(express.static(__dirname + '/public')); Unfortunately, despite my efforts to follow the ad ...