Guard does not prompt router redirection

My angular app running Angular 15 is facing an issue with the App-routing module not redirecting when a guard returns the UrlTree. app-routing.module.ts

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { LoggedInGuard } from './guard/logged-in.guard';

import { HomeComponent } from './component/home-component/home.component';
import { LoginComponent } from './component/login-component/login.component';

const routes: Routes = [
  {
    path: '',
    redirectTo: 'home',
    pathMatch: 'full'
  },
  {
    path: 'home',
    component: HomeComponent,
    canActivate: [LoggedInGuard]
  },
  {
    path: 'login',
    component: LoginComponent
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

The LoggedInGuard sends a POST request and upon receiving a false response, I console logged it. logged-in.guard.ts

import { inject } from '@angular/core';
import { Router, UrlTree } from '@angular/router';

import { AuthService } from '../service/auth.service';

export const LoggedInGuard = () => {
    const authService = inject(AuthService);
    const router = inject(Router);

    authService.isLoggedIn().subscribe(isLoggedIn => {
        console.log(isLoggedIn);
        if (isLoggedIn) {
            return true;
        }
        return router.parseUrl('/login');
    });
};

Even though the console logs false, I am still being redirected to the home path and remaining there without any errors in the console. I have followed the Angular documentation which states that the guard should return boolean or UrlTree, but it does not seem to be redirecting as expected.

Answer №1

In my opinion, attempting it in the following way might be beneficial

  if (userIsLoggedIn) {
        return true;
  }
  this.router.navigate(['login']);
  return false;

If this approach still doesn't yield desired results, please inform me.

Answer №2

It is not recommended to subscribe inside guards. Instead, you can simply return the observable and it will be automatically subscribed.

export const LoggedInGuard = () => {
    const authService = inject(AuthService);
    const router = inject(Router);

    return authService.isLoggedIn().pipe(switchMap((isLoggedIn: boolean) => isLoggedIn ? of(true): router.navigateByUrl('/login')));
};

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 efficiently share sessionStorage among multiple tabs in Angular 2 and access it right away?

My Current Knowledge: I have discovered a way to share sessionStorage between browser tabs by using the solution provided here: browser sessionStorage. share between tabs? Tools I Am Using: Angular 2 (v2.4.4) with TypeScript on Angular CLI base The ...

What is the best way to specify a function parameter as a Function type in TypeScript?

I'm currently delving into the world of TypeScript and I am unsure about how to specify a function parameter as a function type. For instance, in this piece of code, I am passing a setState function through props to a child component. const SelectCity ...

Transforming an Angular formgroup into an object with fewer parameters

I have developed a form in Angular that is functioning perfectly. Now, I am trying to map the form data to a newCustomer object. However, there seems to be an issue with casting the form as the newCustomer object does not have a checkbox field like the for ...

Conceal or eliminate webpack from Angular 2 framework

Currently immersed in an Angular 2 project with TypeScript. Desiring to conceal or eliminate webpack from the developer tool. Came across information about uglify but it remains somewhat puzzling. See the image below for a glimpse of the Chrome Developer ...

Guide to publishing with Chromatic in a Storybook Angular NX workspace

Hey there, I'm looking for some help with running Storybook Chromatic in an NX workspace. My Angular application and libraries are functioning properly when served locally, and I've been able to run stories for my projects without any issues. I ...

implementing an event listener in vanilla JavaScript with TypeScript

Can anyone help me figure out how to correctly type my event listener in TypeScript + Vanilla JS so that it has access to target.value? I tried using MouseEvent and HTMLButtonElement, but I haven't been successful. const Database = { createDataKeys ...

Ensuring the selected date matches any consecutive dates within the dates array in Angular

Imagine if 01/01/2022 is chosen from the input field, and my array of dates looks something like this: ['31/12/2021', '01/11/2021', '02/01/2022'...] In this scenario, when '31/12/2021' and '02/01/2022' are ...

Tips for invoking a function on a react-bootstrap-table component using TypeScript

One issue I'm encountering is trying to cast the "any" bootstrapTableRef to react-bootstrap-table, setting up the ref correctly, or importing it incorrectly. I am struggling to access the method of the imported table. While I found a solution using th ...

Angular Signal computation does not initiate a re-render

I am currently working on sorting an array of signals within my component. To achieve this, I have wrapped the array in a compute function that sorts it. Below is the relevant code snippet: In the Service file: private readonly _lobbies = signal<Lobby ...

What is the rationale behind using :: before display: inline-block in Angular Material MDC's mat-mdc-form-field-error-wrapper, causing substantial padding?

I recently made the switch from Angular Material to Angular Material MDC in preparation for upgrading to Angular 17 from version 15. However, I've noticed that some styles are now broken. One issue I'm facing is a significant padding between the ...

ReactJS Provider not passing props to Consumer resulting in undefined value upon access

Hey there! I've been facing an issue with passing context from a Provider to a consumer in my application. Everything was working fine until suddenly it stopped. Let me walk you through a sample of my code. First off, I have a file named AppContext.t ...

Is there a way to set the size of my unique carousel design?

Having some trouble with my modal image carousel; the dimensions keep shifting for different image sizes. Image 1 Image 2 ...

I'm currently in a situation where I'm trying to update a dependency, but it seems that

I am currently facing a challenge updating Angular from version 12 to version 16. My goal is to integrate the three.js library into my project, which requires Angular CLI version 16 or higher. Although I have successfully updated angular/cli to version 1 ...

Making an Angular 6 HTTP GET call using HTTP-Basic authentication

When attempting to access a URL that requires Basic Authentication, and returns JSON data, what is the proper way to include my username and password in the following HTTP request? private postsURL = "https://jsonExample/posts"; getPosts(): Observable& ...

An easy guide on incorporating external npm modules into Angular 2, such as an encryption library

Within my Angular 2 application (utilizing the SystemJS module manager and Typescript as the scripting language), I am in need of importing an npm module for encryption purposes. This could be either Crypto-JS, Forge-JS, or any alternative that serves the ...

Incorporating a particular JavaScript library into Angular 4 (in case the library doesn't have a variable export)

I am attempting to display the difference between two JSON objects in an Angular 4 view. I have been using a library called angular-object-diff, which was originally created for AngularJS. You can view a demo of this library here: Link I have trie ...

Currency formatting in ionic2 is not working properly when tested on a

Formatting currency in Ionic2 framework can be done like this: {{finalPremium | currency : 'eur' : true :'.2-2' }}. Interestingly, this functionality only appears to function properly in the browser. When tested on an iPhone device, no ...

Angular's change detection is currently inactive

I need to toggle the visibility of a button based on the value of a boolean variable using the Output property. However, I am facing an issue where the button remains hidden even after the variable is updated with a true value. Parent Component.ts showE ...

What is the best way to centralize JSDoc typedef information for easy sharing between different projects?

Currently, I am incorporating @typedef JSDoc comments at the beginning of my Javascript files to define types (primarily to access certain benefits of TypeScript without fully diving into it right now). I'm curious, where can I keep JSDoc typedef inf ...

Warning: Typescript is unable to locate the specified module, which may result

When it comes to importing an Icon, the following code is what I am currently using: import Icon from "!svg-react-loader?name=Icon!../images/svg/item-thumbnail.svg" When working in Visual Studio Code 1.25.1, a warning from tslint appears: [ts] Cannot ...