Invalidating Angular Guards

My goal is to have my auth guard determine access privileges using an observable that periodically toggles a boolean value. My initial approach was as follows:

auth$ = interval(5000).pipe(map((n) => n % 2 === 0));

canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
): Observable<boolean> | Promise<boolean> | boolean {
    return this.auth$;
}

While this method works when the boolean value changes from false to true, it fails to recognize changes in the opposite direction, causing the guard to become inactive.

Answer â„–1

Every time a navigation starts, a guard is activated.

Angular will unsubscribe after receiving the first emit from a guard, using that value to determine whether to allow or prohibit routing.

This means that you cannot emit values periodically in a guard to override the original emitted value.

If you want to achieve this functionality, you can implement it as shown below:


import { Injectable, OnDestroy } from '@angular/core';
import { CanActivate } from '@angular/router';
import { interval, Observable, Subject } from 'rxjs';
import { map, takeUntil, tap } from 'rxjs/operators';

@Injectable({
    providedIn: 'root',
})
export class AuthGuard implements CanActivate, OnDestroy {
    protected readonly auth$: Subject<boolean> = new Subject();
    protected readonly destroy$: Subject<void> = new Subject();

    constructor() {
        interval(5000).pipe(
            map(n => n % 2 === 0),
            tap(value => this.auth$.next(value)),
            takeUntil(this.destroy$),
        ).subscribe();
    }

    public canActivate(): Observable<boolean> {
        return this.auth$;
    }

    // It's recommended to unsubscribe once the guard is no longer needed
    public ngOnDestroy(): void {
        this.destroy$.next();
        this.destroy$.complete();
    }
}

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

Webpack issue arising from the latest Angular update

Each time I initiate ng serve, I encounter the following error. This was not an issue with Angular 11. Generating browser application bundles...Warning: Entry point '@ngbmodule/material-carousel' contains deep imports into 'C:/Users/Göbölà ...

Utilizing a package from your local computer

Due to my current circumstances, I am unable to utilize the npm publish command to release a package on the internet and subsequently use npm install. I also have no intention of publishing it on a remote server like nexus. Is there a method available to ...

Transforming a base64 string into a uint8Array or Blob within Typescript/Angular8

I'm new to handling Base64 encoded strings, uint8Array, and Blobs. I've integrated a pdf viewer library from this repository https://github.com/intbot/ng2-pdfjs-viewer into our Angular 8 web application. I'm facing an issue where I am sendin ...

Incorporating Angular with a python PDF generator library

How can an external Python PDF generator library be integrated with Angular? Please provide a detailed explanation with example. ...

Tips for replacing HTTP response in Angular 4

One of my challenges involves using a specialized HttpService that inherits from Angular's native Http: export class HttpService extends Http { } I am trying to figure out how to intercept/override the response: My attempt to do this looks like: r ...

The usage of the import statement outside a module is not permitted in a serverless Node application

I am currently in the process of migrating a serverless AWS lambda microservices API to TypeScript. My goal is to retain the existing JavaScript files while incorporating more TypeScript files as we progress. However, I am encountering difficulties with co ...

Troubleshooting problems encountered when duplicating an array in JavaScript

I am attempting to utilize properties and flatmap to modify an array without altering the original data. I have implemented this method in two different instances within a single dispatch call in Vue.js when transferring data from parent to children comp ...

Angular 4 incorporating a customized Bootstrap 4 accordion menu for seamless navigation

I am trying to implement a nested menu using a JSON object in Angular 4. Below is the code I have written. <div id="panel-group"> <div class="panel panel-default" *ngFor="let mainItem of objectKeys(my_menu); let i = index"> <div class ...

Using Node.js to efficiently post JSON data in bulk through an API

I am working on a project that involves using Angular2 for the frontend and Nodejs API with 'mssql' NPM package to interact with a Microsoft SQL Server. Everything is functioning as expected, but I'm stuck on one specific task. My challeng ...

What is the best way to include type within a nested object?

How should I properly define types for a nested object structured like the example below? const theme: DefaultTheme = { color: { primary: '#5039E7', secondary: '#372E4B', heading: '#4D5062', }, ...

Effectively Monitoring Angular Router Link Status

Is anyone else facing an issue with router link active not working correctly when navigating to a route with a different ID? The class is applied on the first navigation, but not on subsequent navigations. Any solutions? This is my HTML file: <div clas ...

I am having difficulty accessing the values stored in my cardTiles variable

I am facing an issue with a variable called cardTiles in my Angular 9 component. The variable is defined as cardTitles:Product[] = []; The Product class is defined as follows export class Product{ productName: string;} When I console.log(this.cardTi ...

Issues with Observable<boolean> functionality

Can anyone lend a hand? I'm facing a challenge with this function that is crucial for the application. Typescript File get $approved(): Observable<boolean> { return this.$entries.map(entries => { if (entries.length > 0) { ret ...

Troubleshooting error in Angular 5 with QuillJS: "Parchment issue - Quill unable to

I've been working with the primeng editor and everything seems fine with the editor itself. However, I've spent the last two days struggling to extend a standard block for a custom tag. The official documentation suggests using the quilljs API fo ...

Potential null object in React/TypeScript

Encountering a persistent error here - while the code functions smoothly in plain react, it consistently throws an error in typescript stating "Object is possibly null". Attempts to resolve with "!" have proved futile. Another error logged reads as follow ...

Guide to utilizing services in Angular 2

As I've developed a service with numerous variables and functions, my goal is to inject this service into multiple components. Each component should have the ability to update certain variables within the service so that all variables are updated once ...

Troubleshooting Angular 2 Final Release Visual Studio - encountering issues with finding module name and incorrect module.id path leading to 404 errors

After upgrading to the Angular 2 Final Release (I am using Visual Studio 2015 and TypeScript 1.8), I noticed that my line moduleId: module.id in my components now has a red squiggly underline and displays an error saying cannot find name 'module' ...

Rendering a component in React based on multiple conditions

Checking sessionStorage and another state variable before rendering a component is essential for my application. I want to avoid showing the same message multiple times within the same session. This is how I have implemented it: const addSession = (noteId: ...

Combining Firebase analytics with an Ionic 3 application using the Ionic Native plugin

I placed the GoogleService-Info.plist file at the root of the app folder, not in the platforms/ios/ directory. When I tried to build the app in Xcode, an error occurred in the following file: FirebaseAnalyticsPlugin.m: [FIROptions defaultOptions].deepLin ...

Adding a tooltip to an Angular Material stepper step is a great way to provide

I am trying to implement tooltips on hover for each step in a stepper component. However, I have encountered an issue where the matTooltip directive does not seem to work with the mat-step element. <mat-horizontal-stepper #stepper> <mat-step lab ...