The Router is perhaps one of the most critical when it comes to managing how a Single Page Application (SPA) moves from one view or component to another. Routing mostly requires displaying different views through path configuration but there is usually need to transfer data to other components during navigation.
First of all, it is noteworthy that the RouterState object from Angular’s Router package takes a central position in this mechanism of passing data. RouterState contains information about the current status of the router effectively the status of the route, the parameters and if any data is involved with the route. This feature enables developers to naturally transfer data from one route to another during routing.
Here in this blog, to give detailed knowledge on RouterState in Angular, we focus on the working concept of RouterState and some of the methods the user can use to pass data through the Angular RouterState. Here we’ll discuss it from the most essential appearance up to the sophisticated application, so you will be aware of how to apply this element in your projects.
When you configure routes on an Angular application using the Angular Router it means you specify paths that correspond to the specific components. But there are cases when you want to additionally send more data between these components as users switch between routes. RouterState was a utility that will help you save route data and keep track of the navigation state.
The RouterState is an object, which describes state of the router at a time of creating the object. It is used internally to hold the state of the router, including:
Let us look at the ways in which Angular allows data to be passed between components using the RouterState. The main forms are route's parameters, query's parameters and routing data.
Using Route Parameters :
Route parameters are used to get dynamic values in the URL such as ID or other identifier. It is set in the route configuration and it can be used in the target component In the route configuration.html
// app-routing.module.ts
const routes: Routes = [
{ path: 'product/:id', component: ProductDetailComponent },
];
// product-detail.component.ts
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-product-detail',
templateUrl: './product-detail.component.html',
})
export class ProductDetailComponent {
productId: string;
constructor(private route: ActivatedRoute) {}
ngOnInit(): void {
// Retrieve the 'id' parameter from the route
this.productId = this.route.snapshot.paramMap.get('id');
}
}
Here, the :id in the path lets the product ID being transferred through the URL. In the component, the ActivatedRoute service is used to retrieved the parameter.
Using Query Parameters :
Other forms of passing data in the URL is through query parameters. Query parameters on the other hand are not part of the path but are added to the path after a? symbol. This is helpful for optional parameters and filtering where certain value is not required and have many options to choose from.
// app-routing.module.ts
const routes: Routes = [
{ path: 'products', component: ProductListComponent },
];
// product-list.component.ts
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-product-list',
templateUrl: './product-list.component.html',
})
export class ProductListComponent {
filter: string;
constructor(private route: ActivatedRoute) {}
ngOnInit(): void {
// Retrieve the 'filter' query parameter
this.route.queryParams.subscribe(params => {
this.filter = params['filter'];
});
}
}
In the URL, you could navigate like this: /products?filter=electronics. The component will take the filter query parameter from the ActivatedRoute.
Using Route Data : Another approach used to transfer data between routes is by using the location Tỉnh data property in the route configuration. This helps define data which is static for the particular route once the route is invoked.
// app-routing.module.ts
const routes: Routes = [
{
path: 'profile',
component: ProfileComponent,
data: { title: 'User Profile', description: 'This is your profile' }
}
];
// profile.component.ts
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-profile',
templateUrl: './profile.component.html',
})
export class ProfileComponent {
title: string;
description: string;
constructor(private route: ActivatedRoute) {}
ngOnInit(): void {
// Access the 'data' object from route
this.route.data.subscribe(data => {
this.title = data['title'];
this.description = data['description'];
});
}
}
As for the data property, it is employed as used to pass static information such as a title of a particular page and its description. This data is available from the ActivatedRoute through the data observable.
Using RouterState in Different Scenarios
In more complex interactions, you might want to capture all the RouterState, not just the parameters of the route but also the data about the process of navigation.
The Router service even offers a routerState property through which you may get the complete RouterState object. This can be rather helpful if, for example, you have to monitor the whole route at the time of the navigation.
import { Component } from '@angular/core';
import { Router, NavigationStart, RouterState } from '@angular/router';
import { filter } from 'rxjs/operators';
@Component({
selector: 'app-navigation-state',
templateUrl: './navigation-state.component.html',
})
export class NavigationStateComponent {
constructor(private router: Router) {
// Subscribe to navigation events to get the full router state
this.router.events.pipe(
filter(event => event instanceof NavigationStart)
).subscribe((event: NavigationStart) => {
const routerState: RouterState = event.routerState;
console.log('RouterState:', routerState);
});
}
}
In this code, we follow the NavigationStart event to get the RouterState object which can provide certain specifics of the router state, activated route and query parameters.
Forwarding data via Angular’s RouterState proves to be an efficient technique to pass data in between components in a given navigation. There are ways by which one can pass on data when the user is navigating from one view to the other view like route parameters, query parameters and data property. Learn more about how RouterState works in Angular means introducing more opportunities of creating data driven applications.
Congratulations to this that it serves to control and transfer data through routing, thereby making your application approachable and flexible to construct in order to create smooth user experiences. As we have seen, regardless of whether you are working on simple apps or complex Single Page Applications, it is important to understand how to work with the RouterState of Angular.
Ready to transform your business with our technology solutions? Contact Us today to Leverage Our Angular Expertise.
0