Executing JS script on route change in Angular 6

Viewed 1084

I'm working on a website orignaly developed in vanilla JS and JQuery. Recently we've decided to upgrade our UI to Angular and typescript. We use piwik to monitor our clients activity and the piwik module was made in pure JS. My problem is that whenever the route changes in the site i need to run the piwik script again (in order to bind the piwik events to the components) but the script is'nt executed again because the sites hav'nt refreshed. What i want is to manualy execute the script from the typescript (using JQuery perhaps). All the solutions i saw was to manuylay remove the script from the dom and then add it again but it seems like a hack, is there any way i can execute the script with webpack/JQuery/Any other technology?

1 Answers

The Angular Router itself provides an observable stream.

You could create a route guard that subscribes to the route, when a NavigationEnd event occurs invoke your logic.

constructor(private router: Router) {}

.....

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

It might be worth reading up on Router Events

Assuming piwiki exists in the global scope, you could invoke it using an InjectionToken

I am not familiar with this package at all, however something like:

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

And then invoke it with your constructor

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

This should give you the ability to invoke pwikiPlugin.something()

Related