Does the Angular CanLoad guard only trigger once during the initial lazy load?

Recently, I've come across an interesting issue within my Angular application that consists of lazy-loaded modules.

In one specific module, there is a guard in place to verify if the user decoded from the JWT token is a system admin. If the user meets the criteria, they are granted access to the section; otherwise, they are redirected to the dashboard.

The peculiar aspect of this scenario is that it functions flawlessly only during the initial module load. Subsequent attempts to log out and login with a non-system admin user fail to trigger the CanLoad guard.

I attempted different strategies by implementing (CanActivate and CanActivateChild) interfaces within the same guard, placing the guard in both the app-routing.module.ts and feature-routing.module.ts files under the CanLoad, CanActivate, and CanActivateChild properties of the modules respectively.

However, the CanActivate and CanActivateChild methods never seem to get invoked, while the CanLoad method called from the app-routing.module.ts file executes just once.

Below you can find the content of the is-sys-adm.guard.ts file:

 [guard code goes here...] 

Here's a snippet of the app-routing.module.ts file:

 [routing configuration goes here...] 

And finally, a glimpse into the feature-routing.module.ts file:

 [feature routing details go here...] 

Despite trying different arrangements such as separating the guard into CanActivate, CanActivateChild, and CanLoad, the issue persists. Is there something crucial that I might be overlooking? Is this behavior intentional or should I consider submitting a bug report on the official repository?

Thank you to everyone willing to dedicate time to delve into this matter <3

Answer №1

The `CanLoad` function determines whether the lazy module can be loaded from the server. Once it has been loaded, this check will not occur again unless you refresh the page by pressing F5. It is advisable to declare the loading conditions in both the `CanLoad` (if you want to prevent the code from being loaded at all) and `CanActivate` (if you wish to restrict access after loading).

{
  path: AppRoutes.security,
  canLoad: [SFWIsSysAdmGuard],
  canActivate: [SFWIsSysAdmGuard],
  loadChildren: () => import('./security/security.module').then(mod => mod.SecurityModule)
},

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

How can transparency be adjusted in Three.js using multiple materials?

I've been working on adjusting the transparency of polyhedra that are imported using MTLLoader.js and OBJLoader.js. Below is the code snippet I am using to load a polyhedron: // Model var obj_file_name = file_name + ".obj"; var mtl_file_name = file_n ...

Issue with column-break-before toggle function only operational in Safari

In my website layout, I have arranged li elements in a 2 column design. I am looking to implement a specific functionality where if a div element (inside an li element) is clicked, it should add a class with the following CSS properties: -webkit-column-br ...

Unraveling the Power of Recursive Functions within a React.JS

I'm encountering an issue with a React project. It involves a tic tac toe game where I'm currently working on the implementation of the computer player. The problem arises when the human player clicks on one square (Field-component), triggering ...

Revamping jQuery for a React component

As I transition away from using jQuery for quick hides, shows, and CSS changes in favor of React components that require re-rendering without triggering the jQuery actions requiring a page refresh, I find myself needing to set state within each component. ...

What is the best way to combine individual function declarations in TypeScript?

In my project, I am currently developing a TypeScript version of the async library, specifically focusing on creating an *-as-promised version. To achieve this, I am utilizing the types provided by @types/async. One issue I have encountered is that in the ...

Using onClick function to pass the value of an input textbox in PHP

I have an input text field and I am looking to pass the values entered inside the element through a JavaScript onClick event. <form> <fieldset> <label>Common Site ID: </label><span><?php echo $commonsiteid ?>< ...

Update the numerical data within a td element using jQuery

Is there a way to use jquery to increase numerical values in a <td> element? I've attempted the following method without success. My goal is to update the value of the td cell by clicking a button with the ID "#increaseNum". Here is the HTML st ...

selecting unique elements using classes is not possible with jquery

I am experimenting with using ajax on dynamically generated html elements from django. I have tried selecting the instances by class, but for some reason, it is not working as expected. Can anyone point out my mistake here? javascript $(document).ready(fu ...

When a user clicks on empty space in Angular 2, the page will automatically redirect

When I receive a response from the server, I want to redirect to another page. However, this process takes around 60 seconds, so in the meantime, I want to display a spinner. Once the response is received, I should be redirected to the new page. Sounds sim ...

Creating a loop in Javascript that accesses values from a JSON file and uses the nested data within the loop as a separate JSON object

I am working with a list of user uuids stored in the myContactsUuids array. I am using the forEach() method to iterate through them and add each user, retrieved using the new ChatEngine.User(uuid) function, to the myContacts array. myContactsUuids = ["joh ...

Modifying a single element within a class with Jquery

Is it possible to create a stack of pages on a website using JQuery? I found this image that shows what I'm trying to achieve: image. Instead of applying ID css for each page, I'd like to use JQuery. While researching similar questions, I came ac ...

Encountered a React 16 error: Unexpected TypeError stating that this.state.userInput.map is not a valid

I am working on a simple React app where a user can input text and I want to display each character as a list. Here is the progress I have made so far: App Components import React, { Component } from 'react'; import './App.css ...

nodemon is launching an endless number of .node-xmlhttprequest-sync files

I am facing a strange issue with my app that imports a module containing a promise. Everything runs smoothly when I start the app using "node app.js" However, if I use "nodemon" to launch it, it constantly creates files with names like .node-xmlhttpreque ...

Why am I encountering issues accessing a child property in TypeScript?

Here is some TypeScript code that I am working with: export interface SelectQuery_thing { __typename: "ThingQueryPayload"; content: (SelectQuery_thing_content | null)[]; pageInfo: SelectQuery_thing_pageInfo; } export interface SelectQuery_thing_con ...

The concept of undefined functions and the use of dependency injection may not always align

Recently starting with AngularJs, I am honing my skills by developing a single page Todo Application. However, I have encountered an issue while trying to load a localStorage factory that I intend to use for this project. Currently, I am stuck on the error ...

Model Mongoose TypeScript Interface Type

I am working with 2 models in my project import {model, Schema, Types} from 'mongoose' interface IResource { user : Types.ObjectId | IUsers, type : Types.ObjectId | IResourceData, value : number, lastUpdate : number | Date, ...

Validate the array with AJAX and display an error message

Need assistance validating arrays using FormRequest validation. The error message for the 'name' field can be accessed as data.responseJSON.error.name[0] and displayed to the user. error: function(data, xhr, errmsg, err){ console.log(" ...

Transitioning smoothly from one specific location to another through a scrolling motion

Imagine having a box that is currently off from its correct position due to tranform:translateX(-200px) https://i.sstatic.net/2Mgwm.jpg Just below the picture, there are two <section>'s displayed - one as a large grey box and the other as a whi ...

Express middleware: The functionality of res.statusCode in returning the status code may not be precise

In my Express JS app, I have a simple logging middleware function: app.use(function (req, res, next) { const line = `${req.method} ${req.originalUrl} ${res.statusCode}` console.log(line) next() }) There is also this route in my app: this.app.use(& ...

Exploring the possibilities of TypeScript/angularJS in HTTP GET requests

I am a beginner in typescript and angular.js, and I am facing difficulties with an http get request. I rely on DefinitelyTyped for angular's type definitions. This is what my controller code looks like: module game.Controller { 'use strict& ...