ngEurope: Angular's new router

Rob Eisenberg was at ngEurope to talk about Angular's new router. Rob is the author of Durandal and has recently been added to the Angular team. Together, they took a good look at the different routers out there (SammyJS, EmberJS, Durandal,...). They used what worked and improved what didn't to create a new router for Angular 2.0. What's cool is that they backported it to Angular 1.3. So you can already start using it.

Basic features are what you would expect from a router:

  • configuration
  • 404 handling
  • history manipulationAlso basic for some, but new for Angular:

  • Conventions

  • A navigation model (You will recognize this if you've played with Durandal before. The new router can build a special model that you can use with ng-repeat to generate your navigation.)
  • Document title updatesBut there's more.

Dynamic loading Load controllers on the fly. Again, if you have experience with Durandal, you'll know this is interesting when your application starts to grow. Instead of bundling everything in one download, scripts can now be requested when needed.

Child Apps This is a very cool new feature that will allow large teams to split up their app, library developers to provide a router for their library, etc. What this feature does is it provides the possibility of having a specific router for a specific controller. Say you want to create a library for user management, complete with views, routing, controllers,... You can then easily plug this into your 'parent' app, that of course already has a router.
This also means you could take an entire app and drop it into another app. There are multiple possibilities with this, but one that instantly came to my mind is one big Intranet 'app' that actually consists of multiple sub-apps, all developed by separate teams.

Screen activation It is now possible, with canActivate and canDeactivate, to stop navigation, even if another router is handling the navigation. This can be useful in several cases, for example if the user has unsaved data.
The canDeactivate function is called when we're navigating from a controller. The canActivate is its counterpart, and is called when we're navigating to a controller.
Rob gave the example of a user entering the url of step 2 of a wizard. You could catch this and force the user to finish step 1 first.

Everything in the new router is promise-based, so you can return a promise, but you can still return directly.

Finally, there are navigation commands with which you can take control of the router (for example to redirect the user somewhere).

Rob also went into the design of the router. Basically it's a navigation pipeline, a queue of navigation requests. It is possible to customize this pipeline by pulling out certain steps, or plugging in your own steps.

I'm happy Rob has joined the Angular team and with this new router, this move is already paying off.