Issue with Angular 6 auth guard causing logged-in users to remain on a blank page

I came across this answer and am tweaking it to work with my authentication system: Angular 6 AuthGuard

However, I'm facing an issue where after successful authentication, instead of redirecting to the specified URL, the auth guard leads to a blank page. It works fine when there is no token, as it redirects to the login page.

Although I can see the console output for the "valid token" message, the redirection does not occur. Interestingly, if I include "return true;" at the beginning of the handler function, the forwarding works as expected.

Below is the code snippet from my auth guard service that's causing the problem:

authenticationHandler(): boolean {
    if (this.myToken) {
      this._auth.validateToken(this.myToken)
        .subscribe((result) => {
          if (result.value) {
            // TODO
            console.log('AuthGuard: valid token');

            this.loggedIn.next(true);
            return true;
          } else {
            this.loggedIn.next(false);
            this._router.navigate(['/login']);
            return false;
          }

        });
    } else {
      this.loggedIn.next(false);
      this._router.navigate(['/login']);
      return false;
    }
  }

  canActivate(): boolean {
    return this.authenticationHandler();
  }

Answer №1

In the subscribe function, you are returning true, but this value does not get passed to the route guard. As a result, the route guard returns undefined, which is considered as falsey.

To ensure that the route guard waits for token validation before returning, it is recommended to use async/await syntax.

async authenticationHandler(): Promise<boolean> {
  if (this.myToken) {
    const result = await this._auth.validateToken(this.myToken).toPromise();
    if (result.value) {
        // TODO
        console.log('AuthGuard: valid token');

        this.loggedIn.next(true);
        return true;
     } else {
        this.loggedIn.next(false);
        this._router.navigate(['/login']);
        return false;
     }

  } else {
    this.loggedIn.next(false);
    this._router.navigate(['/login']);
    return false;
  }
}

By using this method, your code will ensure proper validation before exiting the route guard.

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

Is it possible to invoke Cucumber stepDefinitions from a separate project at the same directory level?

Currently, I have a project called integration_test that includes all test projects utilizing cucumberjs, typescript, and nodejs. Project1 contains the login implementation, and I would like to use this implementation in Scenarios from Project2 and Projec ...

Updating Angular 9 Reactive Form: How to Use PatchValue with a Nested FormArray in a FormGroup

I am currently working on maintaining an existing project that involves using a FormGroup helper to transform data into the FormGroup format. The FormGroup includes four nested FormArray elements, and my task is to update all the data within the FormGroup ...

Retrieving information from a JSON object in Angular using a specific key

After receiving JSON data from the server, I currently have a variable public checkId: any = 54 How can I extract the data corresponding to ID = 54 from the provided JSON below? I am specifically looking to extract the values associated with KEY 54 " ...

What is the best way to incorporate a string value from an external file into a variable in TypeScript without compromising the integrity of special characters?

I am encountering an issue with importing a variable from a separate file .ts that contains special characters, such as accents used in languages like French and Spanish. The problem I am facing is that when I require the file, the special characters are ...

Issues with TypeScript "Compile on save" functionality in Visual Studio 2015

The feature of "Compile on save" is not functioning properly for me since I upgraded to Visual Studio 2015. Even though the status bar at the bottom of the IDE shows Output(s) generated successfully after I make changes to a .ts file and save it, the resul ...

What is the most efficient method for line wrapping in the react className attribute while utilizing Tailwind CSS with minimal impact on performance?

Is there a more efficient way to structure the className attribute when utilizing tailwind css? Which of the examples provided would have the least impact on performance? If I were to use an array for the classes and then join them together as shown in e ...

Extend the row of the table according to the drop-down menu choice

I am working on a feature where a dropdown menu controls the expansion of rows in a table. Depending on the option selected from the dropdown, different levels of items need to be displayed in the table. For example, selecting level 1 will expand the first ...

Customize the text color of select list options in Angular 5

Is there a way to style the foreground colors of select list options differently in this dropdown code? <select id="tier" class="form-control" [(ngModel)]="tierId"> <option *ngFor="let m of tierList" value="{{m.tier}}" > {{m.option ...

The Angular AJAX call was unsuccessful due to the Content-Type request header field being forbidden by the Access-Control-Allow-Headers in the preflight response

Here is the code I am using to send a post request from Angular 6 to my web service. const headers = new HttpHeaders({ 'Content-Type': 'application/json' }); const headeroptions = { headers: headers }; return this.http.post(this. ...

The attribute 'name' cannot be found within the class 'MyComponent'

I'm a beginner in Angular2 and I have no previous knowledge of version 1. Can you help me understand why this error is occurring and guide me on how to fix it? import { Component } from 'angular2/core'; @Component ({ selector: 'my- ...

Angular 2 and its commitment

Currently, I am following the Angular 2 tutorial for the Hero App which includes a section on Http requests. You can find the tutorial here. In the hero.service.ts file, there is a method called getHeroes() that makes a call to the server: getHeroes(): ...

The variables declared within the Promise constructor are being identified as undefined by Typescript

In my code, I am creating a let variable named resolver which I intend to set within a promise constructor function. interface Request { ids: string[]; resolver: () => void; promise: Promise<unknown> } class Foo { public requests: ...

Exploring Angular4: Utilizing HttpClient with HttpParams for Passing Object Values in httpParams.set()

I'm facing an issue with handling a more complex key value pair. What if I need to set a value as an object? This is the problem I am encountering: const includeStr = JSON.stringify({include: 'match-timeline-events'}); const params: HttpPa ...

Importing/Requiring an External Module in Typescript Node using a Symbolic Link in the

I am in the process of migrating a Node + Express application to TypeScript and have encountered an issue with using external modules. Previously, I was utilizing the "symlink trick" to avoid dealing with relative paths. This is how it used to work withou ...

What steps can I take to persistently subscribe to SignalR from an Angular service even in the event of connection failures?

Is there a way to safely attempt to connect to SignalR with intervals between attempts until the connection is established? Also, does anyone have advice on how to handle the different stages of connectivity to the web sockets effectively? We are utilizin ...

Error: Unable to retrieve options using this.getOptions function. This issue is unrelated to Vue, it is occurring within

Required Modules "dependencies": { "express": "^4.17.1", "express-static-gzip": "^2.1.1", "react": "^17.0.2", "react-dom": "^17.0.2", "reac ...

Ways to implement logging in an NPM package without the need for a specific logging library

Currently, I am in the process of developing a company npm package using TypeScript and transferring existing code to it. Within the existing code, there are instances of console.log, console.warn, and console.error statements, as shown below: try { c ...

Next.js routes handlers do not have defined methods parameters

Struggling to find the cause of undefined params Currently delving into the world of Nextjs api routes, I keep encountering an issue where my params are coming up as undefined when trying to use them in the HTTP method. My setup includes prisma as my ORM ...

An unusual problem encountered while working with NextJS and NextAuth

In my NextJS authentication setup, I am using a custom token provider/service as outlined in this guide. The code structure is as follows: async function refreshAccessToken(authToken: AuthToken) { try { const tokenResponse = await AuthApi.refre ...

Specializing in narrowing types with two generic parameters

In my current project, I am working on a function that takes two generic parameters: "index" which is a string and "language" which can also be any string. The goal of the function is to validate if the given language is supported and then return a formatt ...