Having trouble registering for router events in Aurelia using TypeScript

It's puzzling why this isn't functioning as expected:)

import {Router, RouterConfiguration} from 'aurelia-router';
import { EventAggregator } from 'aurelia-event-aggregator';
import {autoinject} from 'aurelia-framework';

@autoinject
export class App {
  router: Router;
  ea: EventAggregator;
  navEvent: any;

  constructor(eventAggregator: EventAggregator) {
    this.ea = eventAggregator;
  }

  configureRouter(config: RouterConfiguration, router: Router) {
    config.title = 'Intterra Management';
    config.map([
      { route: ['', 'home'], name: 'home', moduleId: 'home', nav: false, title: '' },
      { route: 'logs', name: 'logs', moduleId: 'logs', nav: true, title: 'Logs' }
    ]);

    this.router = router;
  }

  attached() {
    this.navEvent = this.ea.subscribe('router:navigation:complete', response => {
      localStorage['state'] = location.hash;
    });
  }

  detached() {
    this.navEvent.dispose();
  }
 ...

I have confirmed that the event is triggered during navigation, but the subscribed function does not execute. Any suggestions?

Answer №1

After all the routes and components are set up, the function that is attached will be triggered. If you find that you are subscribing to the event after it has already occurred, make sure to include it in your activate function.

activate() {
  this.navEvent = this.ea.subscribe('router:navigation:complete', response => {
    localStorage['state'] = location.hash;
  });
}

deactivate() {
  this.navEvent.dispose();
}

Answer №2

If you haven't resolved your issue yet, consider directly using this.ea.

this.ea.subscribe("router:navigation:complete", response => {
    localStorage['state'] = location.hash; 
});

Have you thought about subscribing to the event in your constructor as a potential solution?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Does nestjs support typescript version 3.x?

Currently embarking on a new project using Nestjs. I noticed in one of its sample projects, the version of Typescript being used is 2.8. However, the latest version of Typescript is now 3.2. Can anyone confirm if Nest.js supports version 3.x of Typescrip ...

Invoking a Node.js function using a URL reference

Is there a way to call a function located in a remote URL? I have the page URL and the function name. The server-side application is running on NodeJs Express, and the function structure is as follows: function executer(param1, param2){ //logic re ...

Utilizing VueJs (Quasar) to access vuex store within the router

Recently, I have been diving into learning Vuex and creating an authentication module. Following a tutorial, I reached a point where I needed to use the store in the router. However, after importing my store at the top of the router index.js file, I notice ...

How can a loading indicator be displayed while retrieving data from the database using a prop in a tabulator?

Incorporating a tabulator component into my vue app, I have set up the Tabulator options data and columns to be passed via props like this: // parent component <template> <div> <Tabulator :table-data="materialsData" :ta ...

Importance of xpath:position and xpath:attribute

I'm currently developing a recording tool using JavaScript that is comparable to Selenium. When it comes to Playback, I require the XPath position and its attributes (shown in the screenshot below from Selenium). Can anyone provide guidance on how to ...

Personalize Tooltip on Highchart Area Chart

I am currently in the process of customizing the tooltip for my area chart using Highchart. Within this area chart, I have plotted 3 series. My goal is to display the tooltip at a fixed location on the chart's top center. When hovering over any point ...

Tips on how to perform a server-side redirection to a different page in a Nextjs application without refreshing the page while maintaining the URL

I am working on a [slug].js page where I need to fetch data from an API to display the destination page. export async function getServerSideProps({ query, res }) { const slug = query.slug; try { const destination = await RoutingAPI.matchSlu ...

Could you provide me with the list of keywords associated with InstancedBufferGeometry attributes?

When attempting to change the position to position1 in the buffer geometry example provided here, it seems to not function properly. var geometry = new THREE.BufferGeometry(); // create a simple square shape. We duplicate the top left and bottom right // ...

Obtaining the 3D point coordinates from UV coordinates on a 3D plane object using Three.js

I am in the process of creating basic data visualizations using Three.js as my tool of choice. I have a series of PlaneGeometry meshes to which I am applying a transparent texture dynamically generated with red squares drawn at varying opacity levels. My g ...

AngularJS: Modifying values in one div updates data in all other divs

The webpage appears as shown below: https://i.sstatic.net/IxcnK.png HTML <li class="list-group-item" ng-repeat="eachData in lstRepositoryData"> <div class="ember-view"> <div class="github-connection overflow-hidden shadow-oute ...

Absence of a connectivity pop-up within Ionic 2

Whenever the app loads, my "network check" should run automatically instead of waiting for the user to click on the Check Connection button. I tried putting it in a function but couldn't get it to work. Can anyone help me identify the syntax error in ...

Reload iframe content using a .php file within a different iframe

I am currently working on a page that consists of 7 different iframes: <iframe id="leftframe" src="structure/leftbar.php"></iframe> <iframe id="headerframe" src="structure/header.php"></iframe> <iframe id="menuframe" src="struct ...

Problem with YouTube iFrame API in IE when using JavaScript

Apologies for the unclear heading, but I'm facing a peculiar issue. The YouTube iFrame API works perfectly on all browsers except Internet Explorer. In IE, none of the JavaScript code runs initially. However, when I open DevTools and refresh the page, ...

JavaScript: Leveraging arrays as key values

Is there a way in javascript to create an Object with keys as numbers and values as arrays of objects? I am aiming to generate an object structured like this: {Key: "1", value: [Object, Object, ...], key: "2", value: [Object, Object, ...], key:"N", value ...

Exploring the process of implementing smooth transitions when toggling between light and dark modes using JavaScript

var container = document.querySelector(".container") var light2 = document.getElementById("light"); var dark2 = document.getElementById("dark"); light2.addEventListener('click', lightMode); function lightMode(){ contai ...

Angular checkboxes not updating with current values when submitted

I have defined a static array in TypeScript like this: permissions: any[] = [ { permission: "Read", enabled: true }, { permission: "Write", enabled: false }, { permission: "Delete", enabled: false }, { permission: "Edit", enabled: true } ...

When scrolling the page, the onscroll event is activated two times

While practicing a tutorial on modal windows, I came across an interesting issue. After triggering an "onscroll" event at the end of the page and closing the modal window, the event stopped firing. This made me curious as to why the author would include lo ...

Having trouble displaying nested routes in Angular within the view

I'm encountering some issues with child/nested routes in Angular 4. In the app.module.ts file, my imports statement looks like this: RouterModule.forRoot([ { path: 'templates', component: TemplateLandingC ...

Writing and altering content within the <code> element in Chrome is unreliable

Utilizing a WYSIWYG Editor with contenteditable functionality allows users to input "code snippets" using a <code> element. Here is an example: <div contenteditable="true"> <p> This is a paragraph with an <code>inline s ...

Utilizing an object map to pass objects as props without losing their keys

I have an array of objects named obj, structured as follows: { "root": [ { "key": "mihome", "label": "home", "action": "url", ...