ActivatedRouteSnapshot Class to Ease Your Routing Life in Angular

angular
Reading Time: 3 minutes

Routing is the most common and important feature in each and every application perhaps it is a web or a mobile one.
So, In this blog, we are going to talk about the ActivatedRouteSnapshot and its properties which helps the developer to establish the roadmap of routing in an application.

So before diving deep into ActivatedRouteSnapshot let’s start we a question what is ActivatedRouteSnapshot?

What is ActivatedRouteSnapshot?

It is a class that Contains information about a route associated with a component loaded in an outlet at a particular moment in time.

Also, we can traverse the UrlTree.

Characteristics

  1. ActivatedRouteSnapshot is essentially used for debugging.
  2. It uses the Static state for route information.
  3. ActivatedRouteSnapshot exposes the characteristics as plain text values while the others expose them as observables.
  4. This object represents a particular version of ActivatedRoute and is used to determine whether ActivatedRoute can be reused.

UseCase

@Component({templateUrl:'app-home-template.html'})

  class HomeComponent {

   constructor(route: ActivatedRoute) {

    const id: string = route.snapshot.params.id;

    const url: string = route.snapshot.url.join(''); 

    const user = route.snapshot.data.user;

    console.log('id',id);

    console.log('url',url);

    console.log('user',user);


  }
}

When any user hits a new route in an Angular application, the routing uses the browser URL to navigate to the corresponding route and showcase the particular component in the DOM(Document Object Model).

In parallel, it collects the route information to create the instance for that particular route with the help of ActivatedRouteSnapshot.

This instance created through ActivatedRouteSnapshot contains all the information about that route, data, and its parameters. Basically, we can say that this instance helps the ActivatedRouteSnapshot in deciding which components should be rendered for a given route.

Parameter and Properties of ActivatedRouteSnapshot

ActivatedRouteSnapshot have several parameters in routing and some of them are Showcase below:

UrlUrlSegment[]The URL segments matched by this route
queryParamsParamsThe query parameters shared by all the routes
FragmentstringThe URL fragment shared by all the routes
DataDataInformation for the current route
OutletstringOutlet name of the route
routeConfigRouteconfiguration object for that route
urlSegmentUrlSegmentGroupa parsed URL segment group

UrlTree in ActivatedRouteSnapshot

ActivatedRouteSnapshot

For the last stable version of Angular the Router API uses the ActivatedRoute to create the UrlTree and this route must be active and need to appear in the UrlTree. i.e it cannot be empty.

Because of this current process, the UrlSegment of the ActivatedRoute is looked up in the currently active UrlTree of the router. And if the router is empty the UrlTree will not create and shows a failure.

So to resolve the issue the ActivatedRoute initiated a new functionality that allows it to create a UrlTree from an ActivatedRouteSnapshot.

Below are the code structures for both the scenario :

UrlTree without createUrlTreeFromSnapshot.

@Injectable({ providedIn: 'root' })

export class LoginActivatedGuard implements CanActivate {

  constructor(private router: Router, private route: ActivatedRoute) { }

  canActivate(route: ActivatedRouteSnapshot) {
   
  if(checkData(route)) {

      this.router.navigate(['../route2'], { relativeTo: this.route }); 
      
      return false;

    }
    
    return true;
  }

}
const routes: Routes = [{

  path: 'home',

  component: HomeComponent,

  children: [

    {
      path: 'route1',

      component: RouteOneComponent,

      canActivate: [LoginActivatedGuard]

    },

    {

      path: 'route2',

      component: RouteTwoComponent

    }

  ]

}]

UrlTree with createUrlTreeFromSnapshot.

import { Injectable } from '@angular/core';

import { ActivatedRouteSnapshot, createUrlTreeFromSnapshot } from 

'@angular/router';

@Injectable({ providedIn: 'root' })

export class LoginActivatedGuard implements CanActivate {

  canActivate(route: ActivatedRouteSnapshot) {

    if(checkData(route)) {

      return createUrlTreeFromSnapshot(route, ['../route2']);

    }
    
    return true;

  }

}

The CreateUrlTreeFromSnapshot function takes an ActivatedRouteSnapshotcommands, and optional queryParams and fragments and returns a UrlTree.

Conclusion

So after the above, I can say that the ActivatedStateSnapshot provides ease to the routing and helps us to retrieve data/information about the current, and previous route and it also helps us to create the UrlTree.

To learn more about ActivatedRouteSnapshot, ActivatedRoute, and ActivatedstateSnapshot, refer here.

Stay in touch with us!

I hope this blog helped you learn something new and if you liked this blog. Please share it with your friends and colleagues and For more updates on such topics, please follow our LinkedIn page- FrontEnd Studio.

Written by 

Front-End Developer at Knoldus Helping the company to develop and maintain a better code base for reusability. He is recognized as a multi-talented, multitasker, and adaptive to the different work environments. Have experience in technologies such as Angular, Typescript, SCSS, Tailwind and Javascript.

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading