Skip to main content

Dynamically Configuring the Angular's Router

A couple of months ago I wrote “Lazy Loading of Route Components in Angular 2”, where I explained how we can take advantage of the AsyncRoutes and the virtual proxy pattern in Angular 2.
This way we can incrementally load the entire application by only requesting the resources required for the individual views. As result we will decrease the initial load time, which will dramatically improve the user’s experience.
The code for this article is available at my GitHub account.

Problem

This strategy works great! The only things that we need to provide to the AsyncRoute definition are namepath and a loader.
Inside of the loader function we can have whatever custom logic we want to. The only contract that we sign with the framework is that the loader needs to return a promise:
@RouteConfig([
  { path: '/', component: Home, name: 'home' },
  new AsyncRoute({
    path: '/about',
    loader: () => System.import('./components/about/about').then(m => m.About),
    name: 'about'
  })
])
But what if we receive the routes definitions from a remote service and we don’t have them during initialization time?
Well, in such case we need to solve the following three problems:

Referencing not registered routes inside of a template

If we want to reference to a route which is not declared within @RouteConfig by using:
<a [routeLink]="['/not-registered']">Not registered</a>
We will get a runtime error. This means that we need to implement a behavior in which we can list the available at given point of time routes.

Updating the @RouteConfig’s metadata

This is required for consistency. Since the way we register routes in Angular 2 is by using @RouteConfig, we need to make sure that it’s always up-to-date, with all the routes available.

Dynamically registering routes

We need to make the framework aware of the new route definition that we received from the remote service. For this purpose we need to play with the router’s internals, in order to provide the instructions for loading the new route.

Solution

Lets start by exploring the solution of the first problem:

Dynamically rendering the application’s navigation

We can define a component called AppNav which receives a list of objects of the type { name: "Route name", path: ['/Route', 'Path'] } and renders the navigation:
@Component({
  selector: 'app-nav',
  directives: [ROUTER_DIRECTIVES],
  template: `
    <nav>
      <a *ngFor="#route of routes"
        [routerLink]="route.path">
        {{route.name}}
      </a>
    </nav>
  `
})
export class AppNav {
  @Input()
  routes: string[];
}
The component above has a single @Input called routes and uses the ROUTER_DIRECTIVESbecause of the routerLinkdirective. Once the routesproperty changes its template will be populated with the passed value.
We can use this component in the following way:
<app-nav [routes]="[
  { name: 'Route 1', path: ['/Path1'] },
  { name: 'Route 2', path: ['/Path2'] }
]"></app-nav>
So far so good! Now lets see how we can get the list of registered routes and pass them to the directive!

Messing around with the @RouteConfig’s metadata

Lets peek at the semantics of the @RouteConfig decorator. All it does is to add another item to the array of annotations stored as metadata associated with given component. This means that by using the Reflect API we can get all the registered routes!
In order to have better separation of concerns we can isolate the logic for configuring the dynamic routes into a separate class. Lets define a class called DynamicRouteConfigurator, which has the following API:
@Injectable()
class DynamicRouteConfigurator {
  constructor(private registry: RouteRegistry) {}
  // Gets the list of registered with @RouteConfig routes
  // associated with given `component`
  getRoutes(component: Type) {...}
  // Updates the metadata added by @RouteConfig associated
  // with given `component`
  updateRouteConfig(component: Type, routeConfig) {...}
  // Adds additional `route` to given `component`
  addRoute(component: Type, route) {...}
}
Now lets define a root component which uses the AppNav component and DynamicRouteConfiguratorservice we defined:
@Component({
  selector: 'app',
  viewProviders: [DynamicRouteConfigurator],
  templateUrl: './components/app/app.html',
  styleUrls: ['./components/app/app.css'],
  encapsulation: ViewEncapsulation.None,
  directives: [AppNav, ROUTER_DIRECTIVES]
})
@RouteConfig([
  { path: '/', component: HomeCmp, as: 'Home' }
])
export class AppCmp {
  appRoutes: string[][];
  constructor(private dynamicRouteConfigurator: DynamicRouteConfigurator) {...}
  private getAppRoutes(): string[][] {}
}
Now lets explore the definition of getRoutes:

Getting the registered routes

getRoutes(component: Type) {
  return Reflect.getMetadata('annotations', component)
    .filter(a => {
      return a.constructor.name === 'RouteConfig';
    }).pop();
}
Above we simply get all the annotations associated with the passed as argument component and extract the declared routes.

Updating the registered routes

The implementation of updateRouteConfig is quite simple as well:
updateRouteConfig(component: Type, routeConfig) {
  let annotations = Reflect.getMetadata('annotations', component);
  let routeConfigIndex = -1;
  for (let i = 0; i < annotations.length; i += 1) {
    if (annotations[i].constructor.name === 'RouteConfig') {
      routeConfigIndex = i;
      break;
    }
  }
  if (routeConfigIndex < 0) {
    throw new Error('No route metadata attached to the component');
  }
  annotations[routeConfigIndex] = routeConfig;
  Reflect.defineMetadata('annotations', annotations, AppCmp);
}
We loop over all the annotationsin order to find the index of the metadata added by the @RouteConfig decorator and when we find it, we update its value. Right after that we update the annotations using Reflect.defineMetadata(...).

Updating the navigation

We already have the definition of the AppNav component! Now we can get the registered with @RouteConfig routes and render links to all of them.
We can populate the list with the links to the routes using the AppNav component, by setting the appRoutes’ value:
constructor(private dynamicRouteConfigurator: DynamicRouteConfigurator) {
  this.appRoutes = this.getAppRoutes();
  // ...
}

Dynamically registering new routes

Now lets try to asynchronously add another route! We can notice that the DynamicRouteConfigurator has a method called addRoute, so lets use it:
constructor(private dynamicRouteConfigurator: DynamicRouteConfigurator) {
  this.appRoutes = this.getAppRoutes();
  setTimeout(_ => {
    let route = { path: '/about', component: AboutCmp, as: 'About' };
    this.dynamicRouteConfigurator.addRoute(this.constructor, route);
    this.appRoutes = this.getAppRoutes();
  }, 1000);
}
All we do above is to set a timeout for 1 second, define the Aboutroute and add it to the AppCmpusing the injected instance of the DynamicRouteConfigurator. As last step we update the value of the appRoutes which will be reflected by the AppNav component.

Using the RouteRegistry

Now in order to get complete clarity of the entire implementation lets take a look at the addRoute method defined within the DynamicRouteConfigurator:
addRoute(component: Type, route) {
  let routeConfig = this.getRoutes(component);
  routeConfig.configs.push(route);
  this.updateRoutes(component, routeConfig);
  this.registry.config(component, route);
}
As first step we get all the 

registered routes associated with the target component by using getRoutes, later we append one additional route and we invoke the updateRouteConfig method. As last step we register the new route in order to make the framework aware of it. We register it by using the instance of the RouteRegisterpassed as dependency via the DI mechanism of the framework.

Conclusion

Another point for future improvement of the DynamicRouteConfigurator is to allow further modification of the route configuration, such as deletion of existing routes. Although the RouteRegistryallows this functionality we’ll need to touch private APIs (the _routesproperty of the RouteRegistryinstances).

Comments

Popular posts from this blog

4 Ways to Communicate Across Browser Tabs in Realtime

1. Local Storage Events You might have already used LocalStorage, which is accessible across Tabs within the same application origin. But do you know that it also supports events? You can use this feature to communicate across Browser Tabs, where other Tabs will receive the event once the storage is updated. For example, let’s say in one Tab, we execute the following JavaScript code. window.localStorage.setItem("loggedIn", "true"); The other Tabs which listen to the event will receive it, as shown below. window.addEventListener('storage', (event) => { if (event.storageArea != localStorage) return; if (event.key === 'loggedIn') { // Do something with event.newValue } }); 2. Broadcast Channel API The Broadcast Channel API allows communication between Tabs, Windows, Frames, Iframes, and  Web Workers . One Tab can create and post to a channel as follows. const channel = new BroadcastChannel('app-data'); channel.postMessage(data); And oth...

Certbot SSL configuration in ubuntu

  Introduction Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free  TLS/SSL certificates , thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps. Currently, the entire process of obtaining and installing a certificate is fully automated on both Apache and Nginx. In this tutorial, you will use Certbot to obtain a free SSL certificate for Apache on Ubuntu 18.04 and set up your certificate to renew automatically. This tutorial will use a separate Apache virtual host file instead of the default configuration file.  We recommend  creating new Apache virtual host files for each domain because it helps to avoid common mistakes and maintains the default files as a fallback configuration. Prerequisites To follow this tutorial, you will need: One Ubuntu 18.04 server set up by following this  initial ...

Working with Node.js streams

  Introduction Streams are one of the major features that most Node.js applications rely on, especially when handling HTTP requests, reading/writing files, and making socket communications. Streams are very predictable since we can always expect data, error, and end events when using streams. This article will teach Node developers how to use streams to efficiently handle large amounts of data. This is a typical real-world challenge faced by Node developers when they have to deal with a large data source, and it may not be feasible to process this data all at once. This article will cover the following topics: Types of streams When to adopt Node.js streams Batching Composing streams in Node.js Transforming data with transform streams Piping streams Error handling Node.js streams Types of streams The following are four main types of streams in Node.js: Readable streams: The readable stream is responsible for reading data from a source file Writable streams: The writable stream is re...