Last active
November 17, 2019 11:04
-
-
Save ngohungphuc/c0084445656712056a3ff2dd4ea5c5e5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable } from "@angular/core"; | |
import { ApplicationInsights } from "@microsoft/applicationinsights-web"; | |
import { | |
ActivatedRouteSnapshot, | |
ResolveEnd, | |
Router, | |
NavigationStart, | |
NavigationEnd, | |
RouterEvent | |
} from "@angular/router"; | |
import { Subscription } from "rxjs"; | |
@Injectable() | |
export class AppInsightService { | |
private appInsights = new ApplicationInsights({ | |
config: { | |
instrumentationKey: "" // add your app insight key here | |
} | |
}); | |
constructor(private router: Router) { | |
this.appInsights.loadAppInsights(); | |
this.router.events.subscribe( | |
(event: RouterEvent) => { | |
if (event instanceof NavigationStart) { | |
this.appInsights.startTrackEvent("PAGE LOAD TIME"); | |
} | |
if (event instanceof ResolveEnd) { | |
const activatedComponent = this.getActivatedComponent( | |
event.state.root | |
); | |
if (activatedComponent) { | |
this.logPageView(event.urlAfterRedirects); | |
} | |
} | |
if (event instanceof NavigationEnd) { | |
this.appInsights.stopTrackEvent("PAGE LOAD TIME"); | |
} | |
} | |
); | |
} | |
public setUserId(userId: string) { | |
this.appInsights.setAuthenticatedUserContext(userId); | |
} | |
public clearUserId() { | |
this.appInsights.clearAuthenticatedUserContext(); | |
} | |
public logPageView(uri: string) { | |
this.appInsights.trackPageView(uri); | |
} | |
private getActivatedComponent(snapshot: ActivatedRouteSnapshot): any { | |
if (snapshot.firstChild) { | |
return this.getActivatedComponent(snapshot.firstChild); | |
} | |
return snapshot.component; | |
} | |
private getRouteTemplate(snapshot: ActivatedRouteSnapshot): string { | |
let path = ""; | |
if (snapshot.routeConfig) { | |
path += snapshot.routeConfig.path; | |
} | |
if (snapshot.firstChild) { | |
return path + this.getRouteTemplate(snapshot.firstChild); | |
} | |
return path; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment