Tuesday, 5 March 2019

Pass and receive data in Aurelia routes

Aurelia allows for a pretty flexible routing configuration. Your main router can call views which themselves contain sub-routers.

But how do you pass data into those sub-routes? What if your main router gets some data from the server that you don't want to re-get for every sub route?

Let's define a couple of routes, details and payments:

configureRouter(config: RouterConfiguration, router: Router) {
this.router = router;

{ route: ['', 'details'], name: 'Details', moduleId: PLATFORM.moduleName('./view/details'), nav: true, title: "Details", settings: this.data },
{ route: 'payments', name: 'Payments', moduleId: PLATFORM.moduleName('./view/payments'), nav: true, title: "Payments", settings: this.data },

See the settings object at the end of the route? Fairly straight-forward. To access the data in your details route:

activate(params, routeConfig: RouteConfig, navigationInstruction) {
this.data = routeConfig.settings;

Note that the settings object is part of the RouteConfig passed into the activate method, so lets save that to our local this.data property.

There is one gotcha:

You should assign this.data early on in your router, e.g. in the constructor before configureRouter is called. If you use an activate method to get the data don't do this:

activate() {
  this.httpService.getData().then((data) => {
    this.data = data;

Because this.data is undefined when you pass the data to the details route and redefined later, the sub-route will have a reference to the original undefined value.

Instead, do this:

export class View {
  private data: { obj?: SomeType } = {}; // note how this is defined right now, with no contents

  activate() {
    this.httpService.getData().then((data) => {
      this.data.obj = data; // we're not redefining this.data

  // configureRouter() as above

No comments:

Copyright 2009 Another Blog. Powered by Blogger Blogger Templates create by Deluxe Templates. WP by Masterplan