I ended up creating a common service related to everything with AppInsights inspired from here.
import { AngularPlugin, AngularPluginService } from '@microsoft/applicationinsights-angularplugin-js';
import {
ApplicationInsights,
IEventTelemetry,
IExceptionTelemetry
} from '@microsoft/applicationinsights-web';
....
export class ApplicationInsightService {
private appInsights: ApplicationInsights;
constructor(private router: Router, private angularPluginService: AngularPluginService) {
const angularPlugin = new AngularPlugin();
this.angularPluginService.init(angularPlugin, this.router);
this.appInsights = new ApplicationInsights({ config: {
instrumentationKey: 'Your key here',
extensions: [angularPlugin],
extensionConfig: {
[angularPlugin.identifier]: { router: this.router },
}
}});
this.appInsights.loadAppInsights();
this.appInsights.trackPageView();
}
setUserId(userId: string) {
this.appInsights.setAuthenticatedUserContext(userId);
}
clearUserId() {
this.appInsights.clearAuthenticatedUserContext();
}
logPageView(name?: string, uri?: string) {
this.appInsights.trackPageView({ name, uri });
}
logEvent(event: IEventTelemetry, customProperties: { [key: string]: any }) {
this.appInsights.trackEvent(event, customProperties);
}
trackError(exception: Error) {
let telemetry = {
exception,
} as IExceptionTelemetry;
this.appInsights.trackException(telemetry);
}
stopTelemetry() { // !! this is how you stop tracking
this.appInsights.config.disableTelemetry = true;
}
startTelemetry() { // !! this is how you start/re-start it
this.appInsights.config.disableTelemetry = false;
}
}
The JavaScript part of the documentation was not helpful because those methods/properties didn't exist but the C# documentation helped and it seems to be similar to that.