Exploring Angular2: The Router Event NavigationCancel occurring prior to the resolution of the Route Guard

My application has routes protected by an AuthGuard that implements CanActivate. This guard first checks if the user is logged in and then verifies if certain configuration variables are set before allowing access to the route. If the user is authenticated but the necessary configurations are missing, the AuthGuard makes an HTTP call to retrieve them and only permits access once the call is successfully resolved (otherwise denies it).

The problem arises when the Router cancels the navigation before the configuration retrieval process is completed.

Here is the canActivate method of the AuthGuard:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {

        let authenticated = this.isAuthenticated();

        if (authenticated) {
            console.log("User authenticated, checking for configs...");
            if (this.config.defined) {
                console.log("Config defined!");
                return true;
            } else {
                ***** HERE ******
                console.log("Config not defined, setting configs...");
                this.authService.setConfig()
                    .take(1)
                    .subscribe(
                        config => {
                            // SET CONFIG VARIABLES
                            console.log("Config variables set");

                            // allow route access
                            return true;
                        },
                        err => {
                            console.error(err);
                            this.router.navigate(['/Login']);
                            return false;
                        }
                    );
                this.router.navigate(['/Login']);
                return false;
            }
        } else {
            console.log("User not authenticated, back to login");
            this.router.navigate(['/Login']);
            return false;
        }
    }

When I am logged in but the configuration variables are not yet established, and attempt to access a page (marked as **** HERE ****), the console logs:

Setting config...

NavigationCancel {id: 1, url: "/", reason: ""}

NavigationStart {id: 2, url: "/Login"}

RoutesRecognized {id: 2, url: "/Login", urlAfterRedirects: "/Login", state: RouterStateSnapshot}

NavigationEnd {id: 2, url: "/Login", urlAfterRedirects: "/Login"}

Config variables set

Before the AuthGuard's configuration HTTP call can finish, the navigation is cancelled and the router redirects as if the AuthGuard had returned false. I am looking for a solution to ensure that the AuthGuard's result is based on the resolution of the HTTP call.

Answer №1

In case anyone else is facing the same issue, I was able to resolve it by updating the contents of the else block (beginning from *****HERE******) with the code snippet below:

return this.authService.setConfig()
                    .map(
                    config => {
                        // Update configuration variables
                        console.log("Configuration variables updated");

                        // Enable route access
                        return true;
                    })
                    .catch(err => {
                        console.error(err);
                        this.router.navigate(['/Login']);
                        return Observable.of(false);
                    });

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

The browser does not store cookies in its memory

After conducting extensive research on this issue, I have not been able to find a solution yet. In essence, I am currently running a Node.js API server on localhost:3000 and an Angular 10 app on localhost:4200. The problem is straightforward - when I make ...

Learn the process of synchronously loading forms and data in Angular

Looking to synchronize the loading of data and form... Let's start by reviewing the code: ngOnInit() { if (this.data.fromCalendar) { this.singleTraining(); } }, 200); this.formControl(); } formControl() { this.gib ...

The $.each function seems to be stuck and not cycling through the

Dealing with a rather intricate JSON structure, I'm encountering difficulty iterating through it using the $.each() function. It seems to be related to the unusual 2-dimensional array passed in the value section of the standard array (hopefully that m ...

React- Error: Unhandled Type Mismatch in function call for _this4.getNotes

As I delve into learning React, I've created a basic application to manage notes with titles and descriptions. This application interacts with a REST API built using Go, enabling me to perform operations like retrieving, editing, creating, and deleti ...

Coding with a combination of JavaScript, AngularJS, and manipulating brackets

I am currently performing the following action: myArray.push(pageCount); After that, I end up with something like this: $scope.myArray = Pages.getAllPageCount(); Finally, when I utilize AngularJS to display it in my .html file. {{myArray}} If there i ...

What is the method for extracting the types of parameters from a function type while excluding a single parameter?

Suppose I have the following interface that defines a function: export declare interface NavigationGuard { (to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext): NavigationGuardReturn | Promise<NavigationGuardReturn ...

Angular Authentication Functionality

I need to create a loggedIn method in the AuthService. This method should return a boolean indicating the user's status. It will be used for the CanActivate method. Here is a snippet of code from the AuthService: login(email: string, password: string) ...

Angular2 Navigation: Redirecting to a dynamically constructed route

To start, I need to automatically redirect to today's date as the default. Below is the routing configuration I currently have set up: import { CALENDAR_ROUTE } from './_methods/utils'; export const appRoutes: Routes = [ { path: Cal ...

What is the correct method of implementing the "OnChange" event to a WooCommerce select element?

My task is to include the onchange="myFunction()" in the select menu below. However, because the select menu is part of woocommerce, I want to ensure that the onchange="myFunction()" remains intact even after updating my theme. How can I achieve this goal ...

The process of ordering awaits using an asynchronous method

async fetchAndStoreRecords(): Promise<Records[]> { this.subRecords = await this.afs.collection<Records>('records') .valueChanges() .subscribe((data: Records[]) => { console.log('log before data ...

What is the TypeScript equivalent of the Java interface.class?

Can you write a Java code in TypeScript that achieves the same functionality as the code below: Class<?> meta = Object.class; and meta = Processor.class; // Processor is an interface In TypeScript, what would be the equivalent of .class? Specifica ...

Is there a way to assign a dynamic value to an input just once, and then retain the updated value without it changing again

During a for loop, I have an input element (type number) that needs its value modified by decrease and increase buttons: <div class="s-featured-list__item s-featured-list__item--expandable" v-for="(item, itemIndex) in category.items" ...

Steps to create an if statement using jQuery

.data( "autocomplete" )._renderItem = function( ul, item ) { return $( "<li></li>" ) .data( "item.autocomplete", item ) if ( ( item.parent_term_id == "16" ) ) { .append( "<a>" + (item.child_term ? item.child ...

Is it possible to retrieve the value of a particular field from a table?

My goal is to create a table that displays data about various users awaiting admin approval. Each row represents a specific user, and when the approve button on a particular row is clicked, I want to open a new window displaying detailed user information f ...

Halt the program's process until the ajax request has finished

Struggling with what seems like a common issue of the "Asynchronous Problem" and finding it difficult to find a solution. Currently, I am working on a custom bootstrap form wizard which functions as tabs/slideshow. Each step in the wizard is represented b ...

Error: The module '@angular/localize/init' could not be located within the specified directory '/usr/src/app/src'

After upgrading from Angular 8 to 9, I added the @angular/localize package. In my polyfill.ts file, I included the following import: import '@angular/localize/init'; When I compile and run my app locally in a browser, everything works fine. How ...

Learn the art of generating multiple dynamic functions with return values and executing them concurrently

I am currently working on a project where I need to dynamically create multiple functions and run them in parallel. My starting point is an array that contains several strings, each of which will be used as input for the functions. The number of functions ...

An effective method for adding information to a REDIS hash

My current computing process involves storing the results in the REDIS database before transferring them to the main database. At the moment, I handle operations in batches of 10k items per chunk using a separate GAE instance (single-threaded computing wi ...

Align pictures in the middle of two divisions within a segment

This is the current code: HTML: <section class="sponsorSection"> <div class="sponsorImageRow"> <div class="sponsorImageColumn"> <img src="img/kvadrat_logo.png" class="sponsorpicture1"/> </div& ...

Tips for maximizing efficiency and minimizing the use of switch conditions in JavaScript when multiple function calls are needed

After coming up with this code a few minutes ago, I began to ponder if there was a more elegant way to optimize it and condense it into fewer lines. It would be even better if we could find a solution that eliminates the need for the switch condition altog ...