Utilizing the ActivatedRoute component within the canActivate Guard

My understanding is that the call signature of canActivate is as follows:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {

}

I have a service that requires the name of a component and returns the necessary user role to access it. This allows me to check in the canActivate function of my guard whether the active user has the required role. The issue I am facing is that I am unsure how to access the component. My research led me to solutions like this:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
  const nameOfComponent = route.routeConfig.component.name;
  return doSomeRoleCheck(nameOfComponent);
}

However, when implementing this code, I encounter an error: "Cannot read proprty 'name' of undefined". How can I retrieve the component of the current Route and specifically its name as a string?

Edit

I have discovered that this guard is being checked on a parent route. It works when checking on a child route. How can I access the child component from the parent's ActivatedRouteSnapshot?

Answer №1

If you are looking for a solution that fits your specific scenario, consider implementing something along these lines:

export abstract class CheckRole {
  myRoles: string[];
}

@Component({ ... })
export class CustomComponent extends CheckRole {
  public myRoles = ['User', 'Admin'];
}

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
  if (!route.routeConfig.component instanceof CheckRole) {
    // Handle error
  }
  return performRoleCheck(route.routeConfig.component.myRoles)
}

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

Modify the color of the matSnackbar

I'm having trouble changing the snackbar color in Angular using Angular Material. I tried using panelClass in the ts file and adding it to the global css, but the color remains unchanged. Any suggestions on how to resolve this? I am still new to this ...

organizing strings in alphabetical order using TypeScript

My md-collection is set up to display a list of emails like this: <md-collection-item repeat.for="u of user" class="accent-text"> <div class="row"> <di ...

Type inference challenges when overloading functions in TypeScript

What causes the example below to fail during compilation? function mapObjectValues<I, O, K extends keyof any>(obj: Record<K, I>, map: (value: I, key: K) => O): Record<K, O> function mapObjectValues<K extends keyof any, I extends Rec ...

Having difficulty importing my customized TypeScript npm package

Creating a typescript npm package is fairly simple, here's an example: Core.ts class Core{ constructor(){} //some functions } export = Core; Core.d.ts declare class Core { constructor(){} //some functions } export = Core; Package. ...

Invalid input: The provided string is not recognized as a valid number

Currently, I am developing a website with Angular that is linked to an ASP.Net backend for database access. The error I am encountering pertains to a custom Async Validator integrated into a Form Control. This validator serves the purpose of verifying if a ...

Building intricate structures in Typescript: A comprehensive guide

My objective is to create a sophisticated object, with values that need to be calculated or extracted from another object. The specific object I am working on is defined as follows: interface A extends B { key1: string key2: { it's a complex object ...

Global variables in Ionic 2 and Angular 2 are essential for storing data that needs

Recently delving into the realm of Ionic2/Angular 2, I find myself in a state of confusion. Imagine I have a variable within a class structured as follows: export class HomePage { array: string[]; } Here's my query - how can I access the data ...

Does [email protected] come with the AOT Compilation enabled by default?

Is AOT Compilation the default setting for [email protected] and angular/[email protected] ? We are in the process of migrating our apps today, and I'm unsure if the documentation is still up to date: https://angular.io/docs/ts/latest/cookbo ...

Creating an accordion using *ngFor in Angular 8

I'm currently working on creating a dynamic accordion hierarchy using *ngFor and the Bootstrap accordion component. Below is the code I have so far: <div class="container" style="color:black;"> <div id="accordion"> <div cl ...

Why am I receiving information about every single hero in the game?

When I click on "show more," I want to see the details of a specific hero instead of getting all hero details at once. Here are my favorite heroes: <ul *ngFor ="let item of acts;let i =index;"> <li>{{item.name}} `` < ...

Positioning dropup and dropdowns in ng-bootstrap on a single page

Is it possible to have both dropdown and dropup options on the same page using ng-bootstrap? I attempted to implement the code provided in the ng-bootstrap documentation, but it only allows for a global configuration of dropdowns. I specifically need ...

Using RxJs Observables in conjunction with WebSockets for

My angular app is connected to the backend through a websocket for communication. In my test scenario, I have 2 client components. The Observable timer displays two different client ids as expected. When each ngOnInit() is called, it also logs the id of ...

Creating an interface for writing types in Firebase functions/storage/database

What are the TypeScript types for Firebase functions, storage, and admin? I'm fairly new to TypeScript and currently in the process of updating my JavaScript code to TypeScript. Within my code, I am generating a context object. const context = { ...

What is the best way to create a custom interval gap for polling using RxJS in Angular?

Trying to create a gap/delay between each interval call, but the current method is not working as expected. pollOnInterval(threshold = 4000): Observable<any> { let thresholdValue = threshold; const increaseBy = 2000; const maxCount = 10 ...

Using React JS to Sort an Array Based on a Specific String

Here I am again, this time dealing with reactjs. I have a json object containing two "rows", labeled as Description and ubication. My goal is to filter the array based on the Description field. How can I achieve this? The description is in text format, f ...

Vue Deep Watcher fails to activate when the data is altered

While the countdown timer is functioning properly, it seems that the deep watcher is not working as expected. Despite attempting to log the new value of seconds in the console, it does not display anything even though the countdown timer continues to funct ...

React/TypeScript - react-grid-layout: The onDrag event is fired upon clicking the <div> element

I am currently working on creating a grid with clickable and draggable items using the react-layout-grid component. However, I am facing an issue where the drag is instantly activated when I click on the item without actually moving the cursor. Is there a ...

The object { production: boolean; } does not include the property 'firebase'

While attempting to deploy my Angular 4 app on both Firebase and Heroku for production, I encountered the following error: ERROR in /Users/.../... (57,49): Property 'firebase' does not exist on type '{ production: boolean; }'. This ...

Determining the chosen numeral and letter in Angular 8

I am encountering an issue with the selected option, where the name_step = "ABCD" is selected, but when the name_step = "1" is not selected. I am puzzled as to why this is happening, despite setting both as strings. Here is my code snippet: <option ...

Angular: issue with data binding between two components

I am facing an issue with data binding between two components. The first component sends the data as an object, while the second one iterates over it and displays the data in input fields (each value corresponds to an element). My goal is to update the val ...