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

various positions for ngb properties

My input field has both a tooltip and a dropdown attached to it using the ngb attributes: <input placement="right" ngbTooltip="Search" [ngbTypeahead]="search" /> The issue I'm facing is that I want the tooltip to appear on the right ...

A guide to declaring MongoDB models in TypeScript across multiple files

In my Node.js TypeScript project, the structure is as follows: https://i.stack.imgur.com/YgFjd.png The crucial part of the structure lies in mongoModels. I have 2 models where each Category model is connected and contains field category.expertUserIds whi ...

What could be causing the issue with dayjs dynamic importing in TypeScript?

Currently, I am developing a web screen within a .NET application and facing an issue with sending datetime preferences from the system to the web screen using CefSharp settings. AcceptLanguageList = CultureInfo.CurrentUICulture.Name In my TypeScript code ...

Not all generic types specified with an extends clause are appropriately narrowed down as expected

Consider the following scenario: type MyType = 'val1' | 'val2' | 'val3'; const variable = 'val1' as MyType; const val2 = 'val2'; const val3 = 'val3'; declare function test<U extends MyType&g ...

`Express routes in TypeScript`

Recently, I have been following a tutorial on how to build a Node.js app with TypeScript. As part of the tutorial, I attempted to organize my routes by creating a separate route folder and a test.ts file containing the following code: import {Router} fro ...

Prevent selection of future dates and display them in a muted grey color in the p-calendar component

I am attempting to prevent users from selecting future dates and visually distinguish them by setting a grey color background. However, I am having trouble disabling the future dates while the grey color background is functioning correctly. Any ideas on ho ...

What are the best strategies for combining multiple TypeScript class decorators?

I have a set of unique class decorators that I apply to multiple classes. It looks something like this: @awesome @cool @amazing export class MySpecialClass { /* ..... */ } However, since I use these three decorators across many classes, I want to condens ...

How can TypeScript objects be serialized?

Is there a reliable method for preserving type information during JSON serialization/deserialization of Typescript objects? The straightforward JSON.parse(JSON.stringify) approach has proven to have several limitations. Are there more effective ad-hoc sol ...

Unable to get the Angular Formly select option to bind

I'm currently working on binding formly select type options with the following code: fieldGroup: [ { key: 'TimeOffTypeID', type: 'select', className: 'flex-40 padding-10', templateOptions ...

Compilation of Angular 6 project is failing due to error TS1005: Expected ',' instead of the symbol used

I keep encountering an error message whenever I try to compile my code. ERROR in src/app/form/form.component.ts(22,39): error TS1005: ',' expected. Below is the snippet of code where the error is pointing: import { Component, OnInit } from &ap ...

Creating a sequence of HTTP calls that call upon themselves using RxJs operators

When retrieving data by passing pageIndex (1) and pageSize (500) for each HTTP call, I use the following method: this.demoService.geList(1, 500).subscribe(data => { this.data = data.items; }); If the response contains a property called isMore with ...

Is there a way to implement personalized error management in TypeScript with Express?

For a while now, I have been using JavaScript to create my APIs but recently made the switch to TypeScript. However, I keep encountering errors along the way. One particular error handler I have set up is for when a route cannot be found, as shown below: i ...

Issue with VueJS 2 and TypeScript: computed value unable to recognize property specified in data object

When creating the following component: <template lang="html"> <div> <p>{{ bar }}</p> </div> </template> <script lang="ts"> import Vue from 'vue'; export const FooBar = Vue.ex ...

Preventing page refresh with Ionic's alert controller

I'm a beginner in Ionic-Angular and I'm facing an issue with a matautocomplete feature that includes an icon. The problem arises when a value is selected in the matautocomplete, a list should be displayed below. However, when I click on the icon, ...

Tips for resolving the AngularFire migration error related to observables

Recently, I decided to upgrade a project that had been untouched for over a year. Originally built on Angular 10, I made the jump to Angular 12. However, the next step was upgrading AngularFire from v6 to v7, and it appears there is an issue with typings. ...

Error: Uncaught TypeError - Unable to access 'reduce' property of undefined value

Currently, I am focusing on implementing yup validation. Specifically for FileList validation, encountering an issue where leaving the input empty triggers the following error message: enter image description here Below is the code snippet in question: (C ...

Error in Angular multiselect dropdown: Unable to retrieve the length of undefined property

counter: number = 0; getDatatypes(){ if(this.counter == 0) { if(this.appId != 0) { if(undefined != this.datatypes && this.datatypes.length) for (let i = 0; i < this.datatypes.length; i++) { this.ap ...

Ways to dynamically link a JSON response object to an entity?

In my ng2 implementation, I have a user.service.ts file that calls a REST service and returns JSON data. The code snippet below shows how the getUser function retrieves the user information: getUser(id: number): Promise<User> { return this.http. ...

Create a custom component that wraps the Material-UI TextField component and includes default

I have been exploring React and had a question regarding wrapping a component like TextField from mui to add new props along with the existing ones. I attempted to do this but am struggling to figure out how to access the other props. Can anyone help me ...

What is the best way to invoke a function in Typescript while retrieving data?

Is it possible to run a query in my main.ts file with another ts file and then pull the result of the query into another file? If so, how can this be achieved? Here is an example from my main.ts file: async function getAllTips() { const tips: any = []; ...