2
votes

I want message to persist through all pages of my application, and be set after the view-model and view are bounded. Every page I have a very simple template.

<template>
    <h1>${message}</h1>
</template>

The code behind is empty for each page ('Page1', 'Home', 'Page2'). Here is my app.js

import {inject} from 'aurelia-framework';

export class App {

    configureRouter(config, router) {
        config.title = 'Pathways';

        config.map([
                { route: ['','home'], name: 'home', moduleId: 'home', nav: true, title:'Home' },
                { route: 'page1', name: 'page1',  moduleId: 'page1',    nav: true, title:'Page1' }

        ]);
        // Create a binding to the router object
        this.router = router;
    }
    attached() {
        this.message = this.router.currentInstruction.config.title;
    }
}

The problem is, when I first load the app. ${message} is blank. Then, when I navigate to page1, the message becomes Home !! I thought that maybe the currentInstruction was lagging behind, so I added another page. Page2 if you will, but it turns out no matter what I do after the first navigation the message is always Home

So on app initialization message is blank, and then upon the first navigation message will remain Home for the entirety.

My question is, what is the "Aurelia" way to get the title of each page the user is currently on? I would think injecting the router on each page is costly

2

2 Answers

2
votes

I can see two options:

The first and easiest one is using a getter property that listens to router.currentInstruction. For instance:

@computedFrom('router.currentInstruction')
get message() {
  if (this.router.currentInstruction !== null)
    return this.router.currentInstruction.config.title;
}

Running Example https://gist.run/?id=b01abe2859bc2bea1af0f8d21fc2045f

The second option is using the EventAggregator. For example:

attached() {
  this.subscription = this.ea.subscribe('router:navigation:success', () => {
      this.message = this.router.currentInstruction.config.title;
  });
}

detached() {
  this.subscription.dispose(); //remember to always dispose the subscription
}

Running example https://gist.run/?id=7d30d4e8d479cc209ca9013e10e91505

They say we should try to avoid the EventAggregator. So, I'd go with the first option.

1
votes

You can use router.currentInstruction.config.title direct on your app.html page and it will be updated every time then router title is changed (it's using one-way binding):

<h1>title: ${router.currentInstruction.config.title}</h1>

Best way (thanks comments): ${router.currentInstruction.config.navModel.title}