Whenever the return condition is false, make sure to subscribe to the Angular CanActivate Guard

In my UserAccessGuard class, I have a method that captures the current path and compares it to the user's available paths. However, I am facing asynchronous problems because the condition inside the subscribe block causes my Hasaccess variable to remain false since .subscribe is executed after the function has already returned the value.

How can I resolve this issue? Is there a way for the method to return only within the .subscribe block?

@Injectable() export class UserAccessGuard implements CanActivate {

constructor(private router : Router,
    private commonSv : CommonSv) {}

canActivate() : boolean {

    const routesAllowed = this.commonSv.getRoutesAllowed(); //list of strings
    let hasAccess: boolean = false;

    this.router.events.subscribe(
        (event: any) => {
            if (event instanceof NavigationEnd) {
                let matchRoutes = routesAllowed.filter(route => route === this.router.url)
                hasAccess = (matchRoutes.length > 0)
            }
     });

      return hasAccess; //always false because subscribe is executed more last
    }
 }

Answer №1

To achieve the desired outcome, make sure to return an observable that contains either true or false.

canActivate(): Observable<boolean>...

Within the implementation:

return this.router.events.pipe(
    map((event: any) => {
        if (event instanceof NavigationEnd) {
            let matchingRoutes = allowedRoutes.filter(route => route === this.router.url)
            return (matchingRoutes.length > 0)
        }
    })
)

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

How to remove bindings from properties in ngIf with Angular 2+

When using a form with a datepicker, there are certain days where additional fields will be displayed during data entry. An example of this is: <div *ngIf="ticketDate.getDay() === 0" Within this div, I am connecting to some optional properties on my m ...

Making sure to consistently utilize the service API each time the form control is reset within Angular 4

In the component below, an external API service is called within the ngOnInit function to retrieve an array of gifs stored in this.items. The issue arises when the applyGif function is triggered by a user clicking on an image. This function resets the For ...

Delay in Angular routing

As I am still learning Angular, I am trying to familiarize myself with its routing functionality. In my click-through wizard, the final step includes a 'Complete' button that should post to the database and then route the user to a specific page ...

Transforming XML into Json using HTML string information in angular 8

I am currently facing a challenge with converting an XML document to JSON. The issue arises when some of the string fields within the XML contain HTML tags. Here is how the original XML looks: <title> <html> <p>test</p> ...

Union types discriminate cases within an array

Creating a union type from a string array: const categories = [ 'Category A', 'Category B' ] as const type myCategory = typeof categories[number] myCategory is now 'Category A' | 'Category B' Now, the goal is ...

Setting a variable based on the stage of its deployment in a DevOps environment: What you need to know

Is there a way I can easily update a variable in a React app based on the stage of an Azure DevOps release pipeline? For instance, if I have dev, QA, and production stages set up, and I want to change the client ID in the auth configuration for each envi ...

Unexpectedly, a significant ngrx createEffect leads to an unusual error following an update, but the issue vanishes when certain code snippets like tap or filter are disabled

I have been in the process of upgrading a massive Angular 12 project to Angular 13 and have completed several steps. One significant change was the rewriting of Effects using a newer approach like createEffect(() => instead of @Effect However, during ...

The Angular Node server is responding with the error message "You have entered 'undefined' instead of a stream."

Using angular 9 + universal has been smooth sailing until I encountered an issue after building the app with npm run build:ssr and attempting to run it using node: node dist/app/server/main.js. The error message that popped up in the terminal was: Node ...

What steps can be taken to ensure that only users with "admin" status have the ability to edit certain data within a Firebase document?

Within my Angular application, I have implemented Firestore for storing user profiles. Currently, the structure looks like this: /profiles/{uid}/: { displayName: "Luigi",//--> Only editable by Luigi email: "<a href="/cdn-cgi/l/email-protecti ...

Is there a way for me to implement a "view more posts" button on

I need help figuring out how to hide the "Show More" button when there are no posts. I have created a showLoad function and an isLoad state variable, but I'm unsure of how to implement this. The button display logic is dependent on the isLoad state. ...

Develop a TypeScript class in a distinct file

I currently have ag-grid implemented in an Angular project with a CustomFilter. The problem is that the file containing the code for the CustomFilter function is becoming quite large and difficult to manage. I am now looking to move the CustomFilter to a s ...

Angular observable goes unnoticed

I'm venturing into creating my own observable for the first time, and I'm running into issues. The data is visible in the console, but it doesn't show up when the component loads. Can anyone help me troubleshoot this problem? Here's a ...

Troubleshooting Angular 8 Child Routes malfunctioning within a component

I've encountered a peculiar issue – I've cloned ngx-admin and am attempting to utilize the theme as a base theme. I've crafted Layout Components with Modules featuring enabled Routing. The routes function without any hitches when accessed ...

Is it possible to devise a universal click handler in TypeScript that will consistently execute after all other click handlers?

In my ReactJS based application written in TypeScript, we have implemented various click handlers. Different teams contribute to the application and can add their own handlers as well. The challenge we face is ensuring that a specific global click handler ...

"Enhancing Performance with Asynchronous Page Loading in Asp.net WebForms

I have encountered a specific question that I would like to address through discussion. In an asp.net project, there is a WebForm1.aspx with a button. When the client clicks the button, a thread is launched and immediately after that, there is a Response. ...

Issue: Kindly update your dependencies to the latest version of core-js@3

When trying to execute npm start, I encountered an error stating "An unhandled exception occurred: Could not find module "@angular-devkit/build-angular". I attempted to resolve this by installing it using npm install @angular-devkit/build-angular, but the ...

Obtain access to the child canvas element within the parent component

I'm currently working on an app that allows users to sign with a digital pointer. As part of the project, I have integrated react-canvas-signature. My next task is to capture the signature from the canvas and display it in a popup. According to thei ...

Icon for closing Mui Snackbar

I am facing an issue with my notification component that uses the mui snackbar to display alerts. I want to display multiple notifications stacked vertically, but when I try to close one notification using the "Close" icon, it ends up closing both that o ...

Angular - Using the DatePipe for date formatting

Having trouble displaying a date correctly on Internet Explorer using Angular. The code works perfectly on Chrome, Firefox, and other browsers, but not on IE. Here is the code snippet : <span>{{menu.modifiedDate ? (menu.modifiedDate | date : "dd-MM- ...

Is it possible to bind parameters in the select clause using TypeORM?

I'm currently working on implementing a search feature using the pg_trgm module in my PostgreSQL project built with TypeScript and TypeOrm. My SQL query that works for me looks like this: SELECT t, similarity(t, 'word') AS sml FROM test_t ...