Capture Route Parameters in Angular

In Angular, you can capture route parameters for use in your components through the "ActivatedRoute" service. "ActivatedRoute" provides information about the active route, including route parameters.

Here's an example of how you can capture route parameters in a component.

1. Define the Route with Parameters

In the route configuration file (usually "app-routing.module.ts"), define the route with parameters.

// app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { DetailsComponent } from './details/details.component';

const routes: Routes = [
   { path: 'details/:id', component: DetailsComponent },
   // ... other routes
];

@NgModule({
   imports: [RouterModule.forRoot(routes)],
   exports: [RouterModule]
})
export class AppRoutingModule { }

2. Capture Parameters in the Component

In the component associated with the route, you can use the "ActivatedRoute" service to access the parameters.

// details.component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
   selector: 'app-details',
   template: `
     <h2>Item Details</h2>
     <p>ID: {{ id }}</p>
   `
})

export class DetailsComponent implements OnInit {
   id: string;

   constructor(private route: ActivatedRoute) {}

   ngOnInit() {
     // Use 'snapshot' to get parameters at component initialization
     this.id = this.route.snapshot.params['id'];

     // Or use 'subscribe' to watch for parameter changes
     // this.route.params.subscribe(params => {
     // this.id = params['id'];
     // });
   }
}

In the example above, the "id" parameter is defined in the route as ":id". In the "DetailsComponent" component, the "ActivatedRoute" service is injected into the constructor, and the parameters can be accessed using "this.route.snapshot.params['id']". If you want to observe parameter changes while the component is active, use the "subscribe" method.

Remember that if you use "subscribe", it is important to unsubscribe from "ngOnDestroy" to avoid memory leaks. Add the following method to your component:

ngOnDestroy() {
   this.route.params.unsubscribe();
}

This is a common way to capture route parameters in Angular. Be sure to adjust as necessary to meet the specific requirements of your application.

Nenhum comentário:

Postar um comentário

Internet of Things (IoT) and Embedded Systems

The  Internet of Things (IoT)  and  Embedded Systems  are interconnected technologies that play a pivotal role in modern digital innovation....