Running JavaScript code when the route changes in Angular 6

Currently, I am in the process of upgrading a website that was originally developed using vanilla JS and JQuery to a new UI built with Angular and typescript. Our site also utilizes piwik for monitoring client activity, and the piwik module was created in pure JS. The issue I am facing is that whenever there is a route change on the site, the piwik script needs to be executed again in order to bind the piwik events to the components. However, since the sites do not refresh, the script is not executed again. What I am looking for is a way to manually trigger the execution of the script from the typescript (potentially using JQuery). All the solutions I have come across involve removing the script from the dom manually and then adding it back, but this method seems like a workaround. Is there a more efficient way to execute the script using webpack/JQuery or any other technology?

Answer №1

The Angular Router comes with a built-in observable stream.

To create a route guard, you can subscribe to the route and trigger your logic when a NavigationEnd event occurs.

constructor(private router: Router) {}

.....

this.router.events
      .subscribe((event) => {
        if (event instanceof NavigationEnd) {
          console.log('NavigationEnd:', event);
        }
      });

If you want to learn more about Router Events, it would be helpful.

If piwiki is in the global scope, you can call it using an InjectionToken.

I'm not very familiar with this package, but something like this could work:

import { InjectionToken } from '@angular/core';
export const PWIKIPLUGIN = new InjectionToken('PWIKIPLUGIN');

Then you can invoke it in your constructor like this:

constructor(@Inject(PWIKIPLUGIN) private pwikiPlugin) {}

This will allow you to call pwikiPlugin.something().

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

Methods for presenting text from an object array using Angular

I'm running into a bit of trouble with getting my text to show up properly in my code. In the HTML, I have <td>{{cabinetDetails.cabinetType}}</td> and my data source is set as $scope.cabinetDetails = [{cabinetType: 'panel'}]; De ...

Toggling siblings in jQuery when focusing and blurring

Currently, I have this setup that seems to be functioning well. However, I am looking for an optimal way to write it as I am creating a mobile site where performance is crucial. Imagine a tooltip that slides down (toggles) under the element. There are app ...

Lightbox2 is looking to reposition the caption to the right of the image

Can anyone help me understand how to move the caption, found in data-title, from underneath an image to the right of the image? I'm not very familiar with HTML/CSS, but it looks like the image is enclosed within a div called .lb-outerContainer, and t ...

Sending a multi-level property object to the controller in a post request

I am facing a challenge where I need to transfer an object from the view to the controller, and the model comprises a list of objects, each containing another list of complex objects. Let's consider the following models: public class CourseVm { p ...

Receiving encoded characters in the response

URL: I have encountered an issue where I am trying to retrieve the PDF file from the URL above using code. In tools like Postman or Insomnia, I am able to see the output as expected in PDF format. However, when I attempt it with code, I am receiving rando ...

Encounter a parameter validation error

Just a quick question. I have a JS function that takes a parameter as input. If the passed value happens to be NULL, I want to handle it accordingly. However, my limited experience with JS is making it difficult for me to use the correct syntax. Here' ...

An argument error in IE 8 caused by an invalid procedure call

Is there a way to access the opener's class in a child window created using window.open? This works smoothly in W3C browsers, but fails in IE 8. On the other hand, I tested using an iframe and it seems to work fine across all browsers. The main goal o ...

Samsung browser encounters an international error

After developing my web application using Angular2 Rc1, I noticed that it functions perfectly on Safari, Firefox, and Chrome browsers. However, when trying to access the application on my Galaxy S6 using the default browser, an error pops up: https://i.s ...

The issue of Storybook webpack failing to load SCSS files persists

I'm running into an issue where my styles are not loading in Storybook, even though I'm not getting any errors. Can someone help me out? My setup involves webpack 2.2.1. I've scoured Stack Overflow and GitHub for solutions, but nothing seem ...

Troubleshooting: Vue.js not triggering method after watching object

I am in need of watching a prop that is an object, so here is my script: <script> export default { watch:{ filter: { handler:(newval)=> { console.log("I have new data",newval) //this works thi ...

Unable to populate an array with JSON elements within a for loop triggered by useEffect

In my code, there is an issue with the array candleRealTimeDataQueue not updating correctly. Below is the snippet of the problematic code: let candleCurrentJSONDataWS = null; var candleRealTimeDataQueue = []; let tempDateTime = null; let ca ...

Modifying the value of an observable in a component does not automatically activate the subscribe function in a service

In my current situation, I am facing an issue where data sent from a component to a service for manipulation is not triggering the desired behavior. The intention was to update a BehaviorSubject variable in the service by using the next method when fetchin ...

Removing the "<!doctype html>" tag from a document using cheerio.js is a simple process that involves

Is there a way to remove and <?xml ...> from an HTML document that has been parsed by cherio.js? ?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-tran ...

Receiving a form submission via POST method from an external source without redirection

Situation: A user visits site A and submits a form with a hidden input field containing base64 encoded data. The action leads to site B, which is an Angular 2 application. The structure of the form is as follows: <form id="partner" method="POST" actio ...

Is my input file in Javascript valid and does it exist? Here's how to check

In my Javascript code, I am retrieving strings from a text file. When the user inputs an incorrect or invalid file name, I want to display a message. For example: console.log("Your input is invalid"); Here is the code snippet that reads the text file and ...

Using Angular 2: Applying a specific class to a single element with [ngClass]

I have a header table with arrows indicating sorting order, using Bootstrap icons. However, when I click on a column, all columns receive the icon class. Here is an example of what I mean: https://i.sstatic.net/CAS81.png Below is the code snippet: HTML ...

Capturing the action phase in Liferay to change the cursor to 'waiting' mode

I'm currently working on a large Liferay project and have encountered a specific issue: Whenever something in the system is loading or processing, I need to change the cursor to a waiting GIF. While this is simple when using Ajax, there are many inst ...

"Time" for creating a date with just the year or the month and year

I am trying to convert a date string from the format "YYYYMMDD" to a different format using moment.js. Here is the code snippet I am using: import moment from 'moment'; getDateStr(date: string, format){ return moment(date, 'YYYYMMDD&a ...

The scrolling feature is not working in NativeScript's ScrollView component

As I delve into using NativeScript with Angular to develop my debut mobile application, things have been going quite smoothly. However, a recent snag has halted my progress - the page refuses to scroll to reveal its entire content. To showcase this issue, ...

Using HTML, jQuery, and JSON with an AJAX call to populate two web tables stacked on top of each other

I am encountering an issue with populating two tables using two searches based on user input in mySQL-JSON-AJAX. When the user enters a search term and clicks the corresponding button, data should populate the respective table. The problem arises when clic ...