Is there a way to retrieve the Route object in Angular based on a url string?

Is there a way to extract Route object by passing a URL?

interface Route {
    path?: string;
    pathMatch?: string;
    matcher?: UrlMatcher;
    component?: Type<any>;
    redirectTo?: string;
    outlet?: string;
    canActivate?: any[];
    canActivateChild?: any[];
    canDeactivate?: any[];
    canLoad?: any[];
    data?: Data;
    resolve?: ResolveData;
    children?: Routes;
    loadChildren?: LoadChildren;
    runGuardsAndResolvers?: RunGuardsAndResolvers;
}

In my navigation component, I am looking for a way to access the Route information based on a given URL. The Route object's data property contains Access roles that I need. Rather than extracting this information and sharing keys between Routes object and Navigation object, I am exploring options to traverse the Routes object directly.

This is an example of my Navigation object:

{ path: '/maintenance/countries', name: 'Countries' }

The path in the above object is used in a routerLink in the Template. I am seeking a method to leverage this path to retrieve data stored in the Routes object corresponding to that path. Since the Routes object has nested paths, a standard filter wouldn't suffice, leading me to consider utilizing Angular's UrlMatcher.

To summarize, here is a hypothetical scenario of what I aim to achieve:

const foundRoute: Route = this.router.findRoute('/maintenance/countries');
const hasAccess = this.authService.hasAccess(foundRoute.data.roles());

Answer №1

If you access your this.router, you will find that it contains a property called config which holds all the configured routes. To retrieve a specific route, you can use the following code:

const selectedRoute: Route = this.router.config.filter(route => route.path === '/maintenance/countries')[0];

This method works well for "simple" routes without any wildcard characters like *. For more complex routes, you may need to implement a more sophisticated filter function.

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

Effective Approach to Implement Validation in Dynamic Display Column

I have a <mat-select> element in my Angular 7 project with an ngFor loop that displays rows from a table. I need to implement validation for the "type" column, allowing only one key to be selected at a time and preventing users from selecting "key" m ...

Error in React Typescript Order Form when recalculating on change

When creating an order form with React TypeScript, users can input the quantity, unit price, and select whether the item is taxable. In this simplified example, only 1 or 2 items can be added, but in the final version, users will be able to add 10-15 item ...

Discover the steps to trigger a Bootstrap popup modal when clicking on an anchor link using Angular

I have an Angular application and I would like to display a Bootstrap popup modal when the user clicks on a link in the footer. Here is the Bootstrap modal code: <button type="button" class="btn btn-primary" data-toggle="modal&q ...

Descending order of index numbers

I have a table with indexing numbers and when I add a new row, I want the current value to be displayed in the top index number 2. However, my current code is displaying it as 0,1,2 instead of 2,1,0. Here is my HTML file: <mat-table #table [dataSource ...

After the assignment, TypeScript reordered the elements of the array

Dealing with an array of objects for use in a ngFor loop has presented a challenge. The issue arises when the order that was initially set for the array changes unexpectedly due to JavaScript manipulation. Originally, the array is ordered as expected when ...

Unable to attach a tooltip to a list item

As an Angular developer, I am working on a list element that displays all the cars and I am looking to add a tooltip to enhance its visual appeal. Here is what I have attempted so far: I created a span tag with the class "tooltip" to wrap around the ul el ...

Ensure that the variable is not 'undefined' and that it is a single, clean value

In my node backend project, I've encountered a situation with my TypeScript code where a variable occasionally prints as the string 'undefined' instead of just being undefined. Is there a more elegant way to check that the variable is not eq ...

Uncertain about where and how to properly register a service in Angular 2

All: Today was my first day diving into Angular2, as I embarked on the official TUTORIAL at part 6: Routing Around the App https://angular.io/docs/ts/latest/tutorial/toh-pt5.html Within the Create AppComponent section, it is mentioned: Add HeroService ...

Retrieve a specific number from an equation

With my limited knowledge of TypeScript, I am attempting to extract a specific number from an expression. The goal is to locate and retrieve the digit from the following expression. ID:jv.link.weight:234231 In the given string, I aim to extract the numb ...

Blending Angular5 and AngularJS in Polymer

We are considering launching two new projects - one using Angular 5 and the other utilizing Polymer. The second project is intended to serve as a component library for reuse in not only the Angular 5 project but also in other AngularJS projects. After res ...

Is there a way to implement imports based on a specific condition?

I'm just starting to learn Angular and TypeScript. My goal is to redirect multiple hostnames to a single Angular 6 project because most aspects are the same, with only language and URLs varying. For example, here's what I have implemented in ap ...

The module 'PublicModule' was declared unexpectedly within the 'AppModule' in the Angular 4 component structure

My goal is to create a simple structure: app --_layout --public-footer ----public-footer.html/ts/css files --public-header ----public-header.html/ts/css files --public-layout ----public-layout.html/ts/css files In public-layout.html, the stru ...

Navigating URLs to index.html for localized Angular application within lighttpd server - a guide

When deploying an Angular application to a lighttpd server, if a user is browsing example.com/product/12 and sends the link to someone else, they may encounter a 404 error without proper URL rewriting. In this scenario: localized versions are stored in s ...

The data retrieved from the web API is not undergoing the necessary conversion process

I am facing an issue with a web API call where the property checkNumber is defined as a double on the API side, but I need it to be treated as a string in my TypeScript model. Despite having the property defined as a string in my model, it is being receive ...

Angular2 context refers to the 'from' method of Observable

Within the constructor of my Angular2 component class, I have included the following code: Observable.from([1,2,3]).subscribe(e=>{ console.log(e); }); I have made sure to import the necessary modules: import { Observable } from ' ...

Angular CDKScrollable not triggering events

I'm having trouble making the angular CdkScrollable work when creating my own div: <div class="main-section" id="mainsection" #mainsection CdkScrollable> <div class="content" style="height: 300px; backgr ...

Struggling to convert a JSON response into an object model using TypeScript in Angular?

I'm encountering a problem when trying to convert a JSON response into an object. All the properties of my object are being treated as strings, is that normal? Below is my AJAX request: public fetchSingle = (keys: any[]): Observable<Medal> =&g ...

Leveraging the npm package ssh2 in an Angular2 application operating within the Electron framework

My goal is to develop an Angular2 service utilizing the npm package ssh2 - https://www.npmjs.com/package/ssh2. After installing and configuring it, the code for my service can be found below. This code is based on the first example displayed on the ssh2 n ...

Package name "@nx-cloud" is invalid as it does not meet the requirements for Nx 16

Whenever I attempt to install a package in my project, I encounter the following error message: Invalid package name "@nx-cloud" of package "@[email protected]": name can only contain URL-friendly characters. Could this issue be ...

Several mat-radio-button options chosen within mat-radio-group

`<mat-radio-group [ngClass]="cssForGroup" name="test"> <mat-radio-button *ngFor="let option of options | filter:searchText" class="cssForRow" [value]="option" ...