Skip to content

Commit 445175d

Browse files
committed
refactor config into service and expose full implementation
1 parent 7252195 commit 445175d

File tree

5 files changed

+108
-56
lines changed

5 files changed

+108
-56
lines changed

README.md

Lines changed: 31 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,8 @@ $ npm i -S @markpieszak/ng-application-insights
1515
and then add the library to your Angular Root `AppModule`:
1616

1717
```typescript
18-
// Import the Application Insights library
19-
import { ApplicationInsightsModule } from '@markpieszak/ng-application-insights';
18+
// Import the Application Insights module and the service provider
19+
import { ApplicationInsightsModule, AppInsightsService } from '@markpieszak/ng-application-insights';
2020

2121
@NgModule({
2222
imports: [
@@ -28,10 +28,19 @@ import { ApplicationInsightsModule } from '@markpieszak/ng-application-insights'
2828
})
2929
],
3030
// ... providers / etc
31+
providers: [ ..., AppInsightsService ],
3132
})
3233
export class YourRootModule { }
3334
```
3435

36+
and in you app component, import the Application Insights service and inject it in the constructor:
37+
```typescript
38+
import { AppInsightsService } from './app-insights.module';
39+
40+
constructor(..., private appInsightsService: AppInsightsService) {...}
41+
```
42+
43+
3544
## Usage:
3645

3746
Through out your application you can now use the AppInsightsService class to fire off AppInsights functionality.
@@ -53,7 +62,7 @@ export class ShoppingCartComponent {
5362

5463
You can see a list of the API here: https://github.com/Microsoft/ApplicationInsights-JS/blob/master/API-reference.md#class-appinsights
5564

56-
```ts
65+
```typescript
5766
AppInsightsService.trackEvent()
5867
AppInsightsService.startTrackEvent()
5968
AppInsightsService.stopTrackEvent()
@@ -66,6 +75,25 @@ AppInsightsService.trackTrace()
6675
AppInsightsService.trackDependency()
6776
AppInsightsService.flush()
6877
AppInsightsService.setAuthenticatedUserContext()
78+
AppInsightsService.clearAuthenticatedUserContext()
79+
```
80+
81+
## If using SystemJS:
82+
83+
Modify systemjs.config.js...
84+
85+
In System.Config.map, add:
86+
87+
```typescript
88+
'applicationinsights-js': 'npm:applicationinsights-js/JavaScript/JavaScriptSDK.Module/AppInsightsModule.js'
89+
```
90+
91+
and in System.Config.packages, add:
92+
93+
```typescript
94+
'applicationinsights-js': {
95+
defaultExtension: 'js'
96+
}
6997
```
7098

7199
---

index.ts

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,33 @@
1-
import { NgModule, ModuleWithProviders } from '@angular/core';
1+
import { NgModule, ModuleWithProviders, Optional, SkipSelf } from '@angular/core';
22
import { CommonModule } from '@angular/common';
33

4-
import { AppInsightsService } from './src/app-insight.service';
5-
import { provideConfig } from './src/app-insight.config';
4+
import {AppInsightsConfig, AppInsightsService} from './src/app-insight.service';
65

76
export * from './src/app-insight.service';
87

98
@NgModule({
10-
imports: [
11-
CommonModule
12-
],
9+
imports: [ CommonModule ],
1310
declarations: [],
14-
exports: []
11+
exports: [],
12+
providers: [ AppInsightsService ]
1513
})
1614

1715
export class ApplicationInsightsModule {
1816

19-
static forRoot(config: Microsoft.ApplicationInsights.IConfig): ModuleWithProviders {
17+
constructor (@Optional() @SkipSelf() parentModule: ApplicationInsightsModule) {
18+
if (parentModule) {
19+
throw new Error(
20+
'ApplicationInsightsModule is already loaded. Import it in the AppModule only');
21+
}
22+
}
23+
24+
static forRoot(config: AppInsightsConfig): ModuleWithProviders {
2025
return {
2126
ngModule: ApplicationInsightsModule,
2227
providers: [
23-
AppInsightsService,
24-
provideConfig(config)
28+
{ provide: AppInsightsConfig, useValue: config }
2529
]
2630
};
2731
}
2832
}
33+

package.json

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@markpieszak/ng-application-insights",
3-
"version": "1.0.0-rc.0",
3+
"version": "1.0.0-rc.1",
44
"scripts": {
55
"lint": "tslint src/**/*.ts",
66
"test": "tsc && karma start",
@@ -23,23 +23,24 @@
2323
"main": "./dist/index.js",
2424
"dependencies": {
2525
"@angular/router": "^3.4.5",
26-
"@types/applicationinsights-js": "^1.0.1",
2726
"applicationinsights-js": "^1.0.8",
2827
"rxjs": "^5.0.3"
2928
},
3029
"devDependencies": {
31-
"@angular/core": "^2.0.0",
32-
"@angular/common": "^2.0.0",
30+
"@angular/cli": "^1.0.0",
31+
"@angular/common": "^2.4.0",
32+
"@angular/core": "^2.4.10",
3333
"@angular/platform-browser": "^2.4.10",
34+
"@types/applicationinsights-js": "^1.0.1",
35+
"@types/es6-shim": "^0.31.32",
36+
"@types/jasmine": "^2.5.40",
37+
"@types/protractor": "^4.0.0",
38+
"@types/selenium-webdriver": "^2.53.39",
3439
"codelyzer": "^0.0.28",
40+
"rimraf": "^2.5.4",
3541
"tslint": "^3.15.1",
3642
"typescript": "^2.1",
37-
"zone.js": "0.7.2",
38-
"rimraf": "^2.5.4",
39-
"@types/es6-shim": "^0.31.32",
40-
"@types/protractor": "^4.0.0",
41-
"@types/jasmine": "^2.5.40",
42-
"@types/selenium-webdriver": "^2.53.39"
43+
"zone.js": "0.8.4"
4344
},
4445
"engines": {
4546
"node": ">=0.8.0"

src/app-insight.config.ts

Lines changed: 0 additions & 14 deletions
This file was deleted.

src/app-insight.service.ts

Lines changed: 51 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,49 @@
1-
import { Injectable, Inject } from '@angular/core';
1+
import { Injectable, Optional } from '@angular/core';
22
import { Router, NavigationStart, NavigationEnd } from '@angular/router';
33
import { AppInsights } from 'applicationinsights-js';
4-
import { APP_INSIGHTS_CONFIG } from './app-insight.config';
54
import 'rxjs/add/operator/filter';
65
import IAppInsights = Microsoft.ApplicationInsights.IAppInsights;
76

7+
export class AppInsightsConfig implements Microsoft.ApplicationInsights.IConfig {
8+
instrumentationKey?: string;
9+
endpointUrl?: string;
10+
emitLineDelimitedJson?: boolean;
11+
accountId?: string;
12+
sessionRenewalMs?: number;
13+
sessionExpirationMs?: number;
14+
maxBatchSizeInBytes?: number;
15+
maxBatchInterval?: number;
16+
enableDebug?: boolean;
17+
disableExceptionTracking?: boolean;
18+
disableTelemetry?: boolean;
19+
verboseLogging?: boolean;
20+
diagnosticLogInterval?: number;
21+
samplingPercentage?: number;
22+
autoTrackPageVisitTime?: boolean;
23+
disableAjaxTracking?: boolean;
24+
overridePageViewDuration?: boolean;
25+
maxAjaxCallsPerView?: number;
26+
disableDataLossAnalysis?: boolean;
27+
disableCorrelationHeaders?: boolean;
28+
disableFlushOnBeforeUnload?: boolean;
29+
enableSessionStorageBuffer?: boolean;
30+
isCookieUseDisabled?: boolean;
31+
cookieDomain?: string;
32+
isRetryDisabled?: boolean;
33+
isPerfAnalyzerEnabled?: boolean;
34+
url?: string;
35+
isStorageUseDisabled?: boolean;
36+
}
37+
838
@Injectable()
939
export class AppInsightsService implements IAppInsights {
1040
context: Microsoft.ApplicationInsights.ITelemetryContext;
1141
queue: Array<() => void>;
12-
13-
constructor(
14-
@Inject(APP_INSIGHTS_CONFIG) public config: Microsoft.ApplicationInsights.IConfig,
15-
public router: Router
16-
) { }
42+
config: Microsoft.ApplicationInsights.IConfig;
43+
constructor(@Optional() _config: AppInsightsConfig, public router: Router) {
44+
this.config = _config;
45+
this.init();
46+
}
1747

1848
// https://github.com/Microsoft/ApplicationInsights-JS/blob/master/API-reference.md#trackevent
1949
// trackEvent(name: string, properties?: {[string]:string}, measurements?: {[string]:number})
@@ -55,8 +85,8 @@ export class AppInsightsService implements IAppInsights {
5585

5686
// https://github.com/Microsoft/ApplicationInsights-JS/blob/master/API-reference.md#starttrackpage
5787
// startTrackPage(name?: string)
58-
// Starts the timer for tracking a page view. Use this instead of trackPageView if you want to control when the
59-
// page view timer starts and stops, but don't want to calculate the duration yourself. This method doesn't send any
88+
// Starts the timer for tracking a page view. Use this instead of trackPageView if you want to control when the
89+
// page view timer starts and stops, but don't want to calculate the duration yourself. This method doesn't send any
6090
// telemetry. Call stopTrackPage to log the end of the page view and send the event.
6191
startTrackPage(name?: string) {
6292
try {
@@ -68,7 +98,7 @@ export class AppInsightsService implements IAppInsights {
6898

6999
// https://github.com/Microsoft/ApplicationInsights-JS/blob/master/API-reference.md#stoptrackpage
70100
// stopTrackPage(name?: string, url?: string, properties?: Object, measurements?: Object)
71-
// Stops the timer that was started by calling startTrackPage and sends the page view telemetry with the
101+
// Stops the timer that was started by calling startTrackPage and sends the page view telemetry with the
72102
// specified properties and measurements. The duration of the page view will be the time between calling startTrackPage and stopTrackPage.
73103
stopTrackPage(name?: string, url?: string, properties?: {[name: string]: string}, measurements?: {[name: string]: number}) {
74104
try {
@@ -80,7 +110,7 @@ export class AppInsightsService implements IAppInsights {
80110

81111
// https://github.com/Microsoft/ApplicationInsights-JS/blob/master/API-reference.md#trackmetric
82112
// trackMetric(name: string, average: number, sampleCount?: number, min?: number, max?: number, properties?: {[string]:string})
83-
// Log a positive numeric value that is not associated with a specific event.
113+
// Log a positive numeric value that is not associated with a specific event.
84114
// Typically used to send regular reports of performance indicators.
85115
trackMetric(name: string, average: number, sampleCount?: number, min?: number, max?: number, properties?: {[name: string]: string}) {
86116
try {
@@ -94,7 +124,7 @@ export class AppInsightsService implements IAppInsights {
94124
// trackException(exception: Error, handledAt?: string, properties?: {[string]:string}, measurements?: {[string]:number}, severityLevel?: AI.SeverityLevel)
95125
// Log an exception you have caught. (Exceptions caught by the browser are also logged.)
96126
trackException(exception: Error, handledAt?: string, properties?: {[name: string]: string},
97-
measurements?: {[name: string]: number}, severityLevel?: AI.SeverityLevel) {
127+
measurements?: {[name: string]: number}, severityLevel?: AI.SeverityLevel) {
98128
try {
99129
AppInsights.trackException(exception, handledAt, properties, measurements, severityLevel);
100130
} catch (ex) {
@@ -139,7 +169,7 @@ export class AppInsightsService implements IAppInsights {
139169

140170
// https://github.com/Microsoft/ApplicationInsights-JS/blob/master/API-reference.md#setauthenticatedusercontext
141171
// setAuthenticatedUserContext(authenticatedUserId: string, accountId?: string)
142-
// Set the authenticated user id and the account id in this session. Use this when you have identified a specific
172+
// Set the authenticated user id and the account id in this session. Use this when you have identified a specific
143173
// signed-in user. Parameters must not contain spaces or ,;=|
144174
setAuthenticatedUserContext(authenticatedUserId: string, accountId?: string) {
145175
try {
@@ -166,17 +196,19 @@ export class AppInsightsService implements IAppInsights {
166196

167197
public init(): void {
168198
try {
199+
console.warn('in AppInsights.init');
169200
AppInsights.downloadAndSetup(this.config);
201+
console.warn('in AppInsights.init: calling downloadAndSetup');
170202

171203
this.router.events.filter(event => event instanceof NavigationStart)
172-
.subscribe((event: NavigationStart) => {
173-
this.startTrackPage(event.url);
174-
});
204+
.subscribe((event: NavigationStart) => {
205+
this.startTrackPage(event.url);
206+
});
175207

176208
this.router.events.filter(event => event instanceof NavigationEnd)
177-
.subscribe((event: NavigationEnd) => {
178-
this.stopTrackPage(event.url);
179-
});
209+
.subscribe((event: NavigationEnd) => {
210+
this.stopTrackPage(event.url);
211+
});
180212
} catch (ex) {
181213
console.warn('Angular application insights Error [downloadAndSetup]: ', ex);
182214
}

0 commit comments

Comments
 (0)