Let’s hook up some analytics trackers to Angular’s router. Instead of listening in on individual routes, this service needs to know about every route change. Generate a new service and attach it to the routing module with ng g service analytics.
Make sure you’re on the latest version of the Angular CLI. Older versions will fail, with “Error: Specified module does not exist.” |
Open the fresh analytics.service.ts and modify it to add in some structure for recording routing changes:
| import { Injectable } from '@angular/core'; |
| |
| @Injectable({ |
| providedIn: 'root' |
| }) |
| export class AnalyticsService { |
| constructor() { } |
| |
| recordPageChange(event) { |
| // Call your analytics library |
| console.log('Route triggered', event.urlAfterRedirects); |
| } |
| } |
This service just logs any route change to the console. You can import any analytics tool to connect the external tool with Angular. The real excitement goes on in app.component.ts:
| export class AppComponent implements OnInit { |
| title = 'app'; |
| |
① | constructor(private router: Router, private analytics: AnalyticsService) { } |
| |
| ngOnInit() { |
② | this.router.events |
| .pipe( |
③ | filter(event => event instanceof NavigationEnd) |
| ) |
| .subscribe(event => { |
④ | this.analytics.recordPageChange(event); |
| }); |
| } |
| } |
AppComponent now requires injecting both the Router and the newly created AnalyticsService. Don’t forget to import these.
As covered before, router.events is an observable that emits on any event the router might care to send off.
The analytics code only cares about recording page loads, so we filter out any emitted event that isn’t an instance of NavigationEnd.
Finally, inform the analytics code that there’s been a new page change.
There are other events to listen in for, but this serves as a simple example for capturing events on the router. Angular’s RxJS integration also lets you intercept and modify AJAX calls through HttpClient.
3.143.203.96