Getting a URL parameter within the application component

Is it possible to retrieve the hero id parameter from the ApplicationComponent?

const appRoutes: Routes = [
  { path: 'crisis-center', component: CrisisListComponent },
  { path: 'hero/:id',      component: HeroDetailComponent },
  {
    path: 'heroes',
    component: HeroListComponent,
    data: { title: 'Heroes List' }
  },
  { path: '',
    redirectTo: '/heroes',
    pathMatch: 'full'
  },
  { path: '**', component: PageNotFoundComponent }
];

Answer №1

Trying to access the route params from your root component is not feasible since it lacks a defined route.

I can propose two solutions to resolve this issue:

1. Manually parse the params (not very reliable)

ngOnInit() {
  this.router.events
    .pipe(
      filter(e => e instanceof NavigationEnd),
      map((e: NavigationEnd) => e.urlAfterRedirects),
      // parse the url as required
    )
    .subscribe();
}

2. Utilize a dedicated service to share the params (more complex)

Develop a service (named RouteParamsService in this example) to store the current ids. Then access the id within your AppComponent.

HeroComponent

constructor(private route: ActivatedRoute,
            private paramsService: RouteParamsService) {
}

ngOnInit() {
  this.route.paramMap.subscribe(params => this.paramsService.set('heroId', params.get('id')));
}

ngOnDestroy() {
  this.paramsService.delete('heroId');
}

AppComponent

constructor(private paramsService: RouteParamsService) {
}

ngOnInit() {
  this.paramsService.params.subscribe(params => params['heroId']);
}

Answer №2

provides a list of the ID numbers for the URLs

var urlIDs = window.location.pathname.match(/(\d+)/g);
console.log(urlIDs);
console.log('questions/52706460/how-to-obtain-a-url-parameter-in-the-application-component'.match(/(\d+)/g));

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 combine JavaScript objects using TypeScript?

Currently, I am dealing with two objects: First Object - A { key1 : 'key1', key2 : 'key2' } Second Object - B { key1 : 'override a' } I am looking to combine them to create the following result: The Merged Re ...

Error: Component with nested FormGroup does not have a valid value accessor for form control in Angular

In my setup, the parent component is utilizing a FormGroup and I am expecting the child components to notify any changes in value back to the parent. To achieve this, I am trying to implement NG_VALUE_ACCESSOR in the child component so that it can act like ...

Is there a way to verify within the "if" statement without repeating the code?

Is there a way in javascript (or typescript) to prevent redundant object rewriting within an if statement condition? For example: if (A != null || A != B) { // do something here } // can it be done like this: if (A != null || != B) { // avoid repeating ...

"Unlocking the Power of Ionic: A Guide to Detecting Status 302 URL Redirects

Trying to handle a http.post() request that results in a 302 redirect, but struggling to extract the redirected URL. Any tips on how to achieve this? Appreciate any help. ...

Looking to dynamically modify the preselected rows in an Angular Slickgrid grid option when a button is clicked by calling a function (check)

When the button is clicked, certain specific rows are selected using a preselected grid option in Angular Slickgrid. However, if I do this, the preselected row in the grid options changes but it does not display properly. Please assist me. Typescript File ...

Ways to retrieve the document ID or address in TypeScript when using Firestore

I am currently developing a function that will send notifications to all devices where a user is logged in whenever a new order document is added to their account. Below is the code I have written to execute this function. My main query revolves around ac ...

React and TypeScript: Anticipating a function call or assignment but encountered an expression instead

I've developed a signup feature using React and Redux, and have completed all the necessary actions and reducers. However, I encountered the following error: Expected an assignment or function call and instead saw an expression This particular file s ...

TS interfaces: Understanding the distinction between optional and mandatory properties

In this example, I am demonstrating TypeScript interfaces in a simple way: interface A: { id: number; email: string; } interface B extends A { login: string; password: string; } My goal is to have certain requirements when creating objects fr ...

Exploring child components through auxiliary routing in Angular

After defining the root routing as shown below: const routes: Routes = [{ path: '', component: HomeComponent }, { path: 'module1', loadChildren: './module1/module1.module#Module1Module' }, { path ...

Shifting successive elements in an array alternates

I have been working on a pick list component and have come up with the following layout https://i.stack.imgur.com/TnHAp.gif Whenever I try to move consecutive items, it keeps toggling between those two Here's a snippet of my code: moveDown(){ ...

Issue with Angular 8: discrepancy between the value utilized in component.html and the value stored in component.ts (Azure application service)

Encountering a peculiar behavior in one of my Angular applications. In the component.html file, I aim to display "UAT" and style the Angular mat elements with a vibrant orange color when in UAT mode, while displaying them in blue without any mention of UAT ...

Modifying Font Style in Angular 4 Material

Is there a way to change the font in Angular 4 Material material.angular.io using the styles file in .CSS format instead of SASS? While the documentation offers an example for SASS at: https://github.com/angular/material2/blob/master/guides/typography.md ...

Ways to retrieve specific Observable elements?

Having a function like this: getCategories(): Observable<any> { return this.category.find({where: {clientId: this.userApi.getCurrentId()}}) }; The return type of this.category.find is Observable<T[]>. When I invoke g ...

The ngx-datatable is designed to bind only to the final comparator

When utilizing templates with ngx-datatable-column and binding comparator functions, only the final bound comparator is applied to all sortable columns. For instance: <div class="m-333"> <button mat-raised-button color="primary" (click)="openP ...

Issue with the `instanceof` operator not functioning properly when used with Immutable.js

We've encountered an issue while upgrading our project from typescript2.4 to typescript3.2 specifically with immutable.js. Prior to the update, simply using if(x instanceof Immutable.Iterable) would result in the type of x being Immutable.Iterable< ...

"Implement a specific background-color for a component in Angular 4 by adding it to the body tag

My project is built on angular 4, and I am looking to change the background color of the <body> tag using the component's .ts file when a specific element is clicked. The issue I'm facing is that once the color is changed to blue, it persi ...

The journey of communication: uncovering the essence of @input between parent and

I'm diving into Angular and currently working on the @Input phase. Within my main app, there's a child component. Inside app.component.ts, I've declared a test variable that I wish to pass from app.component.ts to child.component.ts. // ap ...

Testing the window object using Jest

I have created a function that simulates a hostname. This function is defined before the actual test, prior to the describe block. const mockHost = (hostname: string) => { global.window = Object.create(window); Object.defineProperty(window, ' ...

Ways to retrieve form information from a POST request

I received a POST request from my payment gateway with the following form data: Upon trying to fetch the data using the code snippet below, I encountered errors and gibberish content: this.http .post<any>('https://xyz.app/test', { ti ...

Combining Babel with Typescript, utilizing NPM modules, and optimizing with Webpack

Hey there! I've been trying to include Angular in my TypeScript script, but unfortunately I keep encountering this error: error TS2307: Cannot find module 'angular'. I have attached my webpack configuration file below: context: __dirname ...