|
1 |
| -import { Injectable } from '@angular/core'; |
| 1 | +import { Injectable, OnInit } from '@angular/core'; |
| 2 | +import { ApplicationInsights } from '@microsoft/applicationinsights-web'; |
| 3 | +import { ActivatedRouteSnapshot, ResolveEnd, Router } from '@angular/router'; |
| 4 | +import { filter } from 'rxjs/operators'; |
| 5 | +import { Subscription } from 'rxjs'; |
2 | 6 |
|
3 | 7 | @Injectable({
|
4 | 8 | providedIn: 'root'
|
5 | 9 | })
|
6 | 10 | export class ApplicationInsightsService {
|
7 | 11 |
|
8 |
| - constructor() { } |
| 12 | + private routerSubscription: Subscription; |
| 13 | + |
| 14 | + private appInsights = new ApplicationInsights({ |
| 15 | + config: { |
| 16 | + instrumentationKey: '...' |
| 17 | + } |
| 18 | + }); |
| 19 | + |
| 20 | + constructor(private router: Router) { |
| 21 | + this.appInsights.loadAppInsights(); |
| 22 | + this.routerSubscription = this.router.events.pipe(filter(event => event instanceof ResolveEnd)).subscribe((event: ResolveEnd) => { |
| 23 | + const activatedComponent = this.getActivatedComponent(event.state.root); |
| 24 | + if (activatedComponent) { |
| 25 | + this.logPageView(`${activatedComponent.name} ${this.getRouteTemplate(event.state.root)}`, event.urlAfterRedirects); |
| 26 | + } |
| 27 | + }); |
| 28 | + } |
| 29 | + |
| 30 | + setUserId(userId: string) { |
| 31 | + this.appInsights.setAuthenticatedUserContext(userId); |
| 32 | + } |
| 33 | + |
| 34 | + clearUserId() { |
| 35 | + this.appInsights.clearAuthenticatedUserContext(); |
| 36 | + } |
| 37 | + |
| 38 | + logPageView(name?: string, uri?: string) { |
| 39 | + this.appInsights.trackPageView({ name, uri }); |
| 40 | + } |
| 41 | + |
| 42 | + private getActivatedComponent(snapshot: ActivatedRouteSnapshot): any { |
| 43 | + if (snapshot.firstChild) { |
| 44 | + return this.getActivatedComponent(snapshot.firstChild); |
| 45 | + } |
| 46 | + |
| 47 | + return snapshot.component; |
| 48 | + } |
| 49 | + |
| 50 | + private getRouteTemplate(snapshot: ActivatedRouteSnapshot): string { |
| 51 | + let path = ''; |
| 52 | + if (snapshot.routeConfig) { |
| 53 | + path += snapshot.routeConfig.path; |
| 54 | + } |
| 55 | + |
| 56 | + if (snapshot.firstChild) { |
| 57 | + return path + this.getRouteTemplate(snapshot.firstChild); |
| 58 | + } |
| 59 | + |
| 60 | + return path; |
| 61 | + } |
9 | 62 | }
|
0 commit comments