Code Monkey home page Code Monkey logo

applicationinsights-angularplugin-js's Introduction

Microsoft Application Insights JavaScript SDK - Angular Plugin

Angular CI npm version

Angular Plugin for the Application Insights Javascript SDK, enables the following:

Note: Angular plugin is NOT es3 compatible

  • Tracking of router changes
  • Tracking uncaught exceptions

Angular Plugin for the Application Insights Javascript SDK

Getting Started

Install npm package:

npm install @microsoft/applicationinsights-angularplugin-js

Basic Usage

Set up an instance of Application Insights in the entry component in your app:

import { Component } from '@angular/core';
import { ApplicationInsights } from '@microsoft/applicationinsights-web';
import { AngularPlugin } from '@microsoft/applicationinsights-angularplugin-js';
import { Router } from '@angular/router';

//-------------------------------------------------------------------------
// Special Note: If you also want to use the ErrorService you MUST include
// either the '@microsoft/applicationinsights-web' or include the
// `@microsoft/applicationinsights-analytics-js' extension, if you don't
// then unhandled errors caught by the error service will not be sent
//-------------------------------------------------------------------------

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
    constructor(
        private router: Router
    ){
        var angularPlugin = new AngularPlugin();
        const appInsights = new ApplicationInsights({ config: {
        instrumentationKey: 'YOUR_INSTRUMENTATION_KEY_GOES_HERE',
        extensions: [angularPlugin],
        extensionConfig: {
            [angularPlugin.identifier]: { router: this.router }
        }
        } });
        appInsights.loadAppInsights();
    }
}

To track uncaught exceptions, setup ApplicationinsightsAngularpluginErrorService in app.module.ts:

Note: When using the ErrorService there is an implicit dependency on the @microsoft/applicationinsights-analytics-js extension which is also include in the that your MUST include the @microsoft/applicationinsights-web Sku, so for uncaught exceptions to be tracked your project MUST be initialized to include the analytics package otherwise unhandled errors caught by the error service will not be sent

import { ApplicationinsightsAngularpluginErrorService } from '@microsoft/applicationinsights-angularplugin-js';

//-------------------------------------------------------------------------
// Special Note: The Errorservice has an implicit dependency on the
// `@microsoft/applicationinsights-analytics-js' extension, which is included
// with the '@microsoft/applicationinsights-web' module, if the analytics 
// extension is not included during initialization of the SDK this Error Service
// will not be able to send any caught unhandled errors.
//-------------------------------------------------------------------------

@NgModule({
  ...
  providers: [
    {
      provide: ErrorHandler,
      useClass: ApplicationinsightsAngularpluginErrorService
    }
  ]
  ...
})
export class AppModule { }

To chain more custom error handlers, create custom error handlers that implement IErrorService:

import { IErrorService } from '@microsoft/applicationinsights-angularplugin-js';

export class CustomErrorHandler implements IErrorService {
    handleError(error: any) {
        ...
    }
}

And pass errorServices array through extensionConfig:

extensionConfig: {
        [angularPlugin.identifier]: {
          router: this.router,
          errorServices: [new CustomErrorHandler()]
        }
      }

Multiple Instance Setup Method

When multiple angualr plugin instance is running in the same session, their error service may overlapped each other and cause conflicts. Therefore, we allow user to use injector so that they could walk around this problem.

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
    constructor(
        private router: Router,
        injector: Injector
    ){
        var angularPlugin = new AngularPlugin(injector);
        const appInsights = new ApplicationInsights({ config: {
        instrumentationKey: 'YOUR_INSTRUMENTATION_KEY_GOES_HERE',
        extensions: [angularPlugin],
        extensionConfig: {
            [angularPlugin.identifier]: { router: this.router, useInjector: true }
        }
        } });
        appInsights.loadAppInsights();
    }
}

The way to init injector would be

const injector: Injector = Injector.create({
    providers: [
        { provide: ApplicationinsightsAngularpluginErrorService, useClass: ApplicationinsightsAngularpluginErrorService }
    ]
});

Compatibility Matrix

As part of updating to support ApplicationInsights 3.x we will be bumping the major version number of this extension to match the major version of the supported Angular version (which will be v14.x for the first release).

Additionally, as part of this change the existing v3.x extension has been moved into the release3.x branch

Version Application Insights Angular Branch
15.1.2 ^3.1.2 peer: ^15.2.9 main
15.1.1 (deprecated) ^3.1.1 peer: ^15.2.9 main
15.1.0 ^3.1.0 peer: ^15.2.9 main
15.0.2 ^3.0.8 peer: ^15.2.9 main
15.0.1 ^3.0.5 peer: ^15.2.9 main
15.0.0 ^3.0.3 peer: ^15.2.9 main
14.0.0 ^3.0.3 peer: ^14.0.3 Angular14 (Angular v14 support is moved to branch Angular14 since Sep. 2023)
3.0.3 ^2.8.14 peer: ^14.0.3 release3.x
3.0.2 ^2.8.12 peer: ^14.0.3 main
3.0.1 ^2.8.10 peer: ^14.0.3 main
3.0.0 ^2.8.5 peer: ^14.0.3 main
2.9.2 ^2.8.5 peer: ^13.0.3 main (Angular v13 support archived to Angular13 branch)
2.9.1 ~2.8.2 peer: ^13.0.3 main
2.9.0 ~2.8.1 peer: ^13.0.3 main
2.8.1 ~2.7.4 peer: ^13.0.3 main
2.8.0 ^2.7.3 peer: ^13.0.3 main
2.7.2 ~2.7.5 peer: ^11.0.6 Angular11
2.7.1 ~2.7.4 peer: ^11.0.6 Angular11

Previous releases where from the ApplicationInsights-JS repo with archived angularplugin-legacy Branch and previous Release Notes

Note

Angular plugin is using newer version of typescript, make sure to build and test before you create a pull request. Navigate to the root folder of Angular plugin, under /applicationinsights-angularplugin-js:

npm install
npm run build
npm run test

Testing

npm run test will run the tests once and exit

npm run watch will run the tests and watch for changes

Contributing

This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com.

When you submit a pull request, a CLA bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

Data Collection

As this SDK is designed to enable applications to perform data collection which is sent to the Microsoft collection endpoints the following is required to identify our privacy statement.

The software may collect information about you and your use of the software and send it to Microsoft. Microsoft may use this information to provide services and improve our products and services. You may turn off the telemetry as described in the repository. There are also some features in the software that may enable you and Microsoft to collect data from users of your applications. If you use these features, you must comply with applicable law, including providing appropriate notices to users of your applications together with a copy of Microsoft's privacy statement. Our privacy statement is located at https://go.microsoft.com/fwlink/?LinkID=824704. You can learn more about data collection and use in the help documentation and our privacy statement. Your use of the software operates as your consent to these practices.

Trademarks

This project may contain trademarks or logos for projects, products, or services. Authorized use of Microsoft trademarks or logos is subject to and must follow Microsoft's Trademark & Brand Guidelines. Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship. Any use of third-party trademarks or logos are subject to those third-party's policies.

License

MIT

applicationinsights-angularplugin-js's People

Contributors

dependabot[bot] avatar ggarbereder avatar karlie-777 avatar microsoftopensource avatar msnev avatar sesa488565 avatar siyuniu-ms avatar timdeschryver avatar xiao-lix avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

applicationinsights-angularplugin-js's Issues

Don't swallow exceptions

Hi,

We're currently having the problem that once the error handler is implemented all errors and exceptions are swallowed even if there is no app insights started. Especially in development mode this is a big problem.

As a workaround I've now created a custom error handler but the problem is that without an instrumentation key I can't create the app insights object to pass the error handler via extensionConfig. I've now set up a switch that if appinsights is not created (no instrumentation key in config) then I call:

if (config.instrumentationKey) {
  this.appInsights = new ApplicationInsights({
    config: {
      ...
      extensions: [angularPlugin],
      extensionConfig: {
        [angularPlugin.identifier]: {
          router: this.router,
          errorServices: [new CustomErrorHandler()],
        },
      },
     ...
    },
  });
} else {
  ApplicationinsightsAngularpluginErrorService.instance.addErrorHandler(
    new CustomErrorHandler()
  );
}

This seem to work but I'm not sure if that is the correct way to do it and I think that the error handler itself should provide such functionality.

Angular unit testing by mocking ApplicationInsights with AI connection string.

I need to write an angular unit testing by mocking an Application Insight object without using a connection string. Please find the code. when I write TC with a dummy string it throws an error on getTraceID (this.appInsights.context.telemetryTrace.traceID) that Please provide instrumentation key.

import { Injectable } from '@angular/core';
import { ApplicationInsights, DistributedTracingModes } from '@microsoft/applicationinsights-web';
import { environment } from '../../../environments/environment';
import { AngularPlugin } from '@microsoft/applicationinsights-angularplugin-js';
import { Router } from '@angular/router';

@Injectable({
    providedIn: 'root'
})
export class MonitoringService {
    private appInsights: ApplicationInsights;

    constructor(private router: Router) {
        this.setupApplicationInsights();
    }

    setupApplicationInsights() {
        if (environment.applicationInsights.connectionString) {
            const angularPlugin = new AngularPlugin();
            this.appInsights = new ApplicationInsights({
                config: {
                    connectionString: environment.applicationInsights.connectionString,
                    autoTrackPageVisitTime: true,
                    distributedTracingMode: DistributedTracingModes.W3C,
                    isBeaconApiDisabled: false,
                    enableCorsCorrelation: true,
                    enableAutoRouteTracking: true,
                    enableAjaxPerfTracking: true,
                    enableAjaxErrorStatusText: true,
                    enableRequestHeaderTracking: true,
                    enableResponseHeaderTracking: true,
                    enableUnhandledPromiseRejectionTracking: true,
                    disableCookiesUsage: true,
                    extensions: [angularPlugin],
                    extensionConfig: {
                        [angularPlugin.identifier]: {
                            router: this.router
                        }
                    }
                }
            });

            this.appInsights.loadAppInsights();

            const telemetryInitializer = (envelope) => {
                envelope.tags['ai.cloud.role'] = environment.applicationInsights.role;
            };
            this.appInsights.addTelemetryInitializer(telemetryInitializer);
        }
    }

    getTraceID(): string {
        return this.appInsights.context.telemetryTrace.traceID;
    }
}

import { TestBed } from '@angular/core/testing';

import { MonitoringService } from './monitoring.service';
import any = jasmine.any;

describe('MonitoringService', () => {
    let service: MonitoringService;

    beforeEach(() => {
        TestBed.configureTestingModule({});
        service = TestBed.inject(MonitoringService);
    });

    it('should be created', () => {
        expect(service).toBeTruthy();
    });
    it ('should create app-insight and get traceID', () => {
        expect(service.getTraceID()).toEqual(any(String));
    });
});

Error Message

Error: Please provide instrumentation key
	    at throwError (node_modules/@microsoft/applicationinsights-web/node_modules/@microsoft/applicationinsights-core-js/dist-esm/JavaScriptSDK/HelperFuncs.js:529:11)
	    at AppInsightsCore.apply (node_modules/@microsoft/applicationinsights-web/node_modules/@microsoft/applicationinsights-core-js/dist-esm/JavaScriptSDK/BaseCore.js:51:31)
	    at Object.initialize (node_modules/@microsoft/dynamicproto-js/lib/dist/esm/dynamicproto-js.js:216:28)
	    at AppInsightsCore.apply [as initialize] (node_modules/@microsoft/applicationinsights-web/node_modules/@microsoft/applicationinsights-core-js/dist-esm/JavaScriptSDK/AppInsightsCore.js:24:23)
	    at AppInsightsCore.initialize (node_modules/@microsoft/dynamicproto-js/lib/dist/esm/dynamicproto-js.js:324:29)
	    at func (node_modules/@microsoft/applicationinsights-web/dist-esm/Initialization.js:324:24)
	    at doPerf (node_modules/@microsoft/applicationinsights-web/node_modules/@microsoft/applicationinsights-core-js/dist-esm/JavaScriptSDK/PerfManager.js:176:12)
	    at Initialization.loadAppInsights (node_modules/@microsoft/applicationinsights-web/dist-esm/Initialization.js:317:15)
	    at MonitoringService.setupApplicationInsights (src/app/share/services/monitoring.service.ts:43:30)
	    at new MonitoringService (src/app/share/services/monitoring.service.ts:14:14)
	TypeError: Cannot read properties of undefined (reading 'getTraceID')
	    at UserContext.apply (src/app/share/services/monitoring.service.spec.ts:18:24)
	    at _ZoneDelegate.invoke (node_modules/zone.js/fesm2015/zone.js:372:26)
	    at ProxyZoneSpec.onInvoke (node_modules/zone.js/fesm2015/zone-testing.js:287:39)
	    at _ZoneDelegate.invoke (node_modules/zone.js/fesm2015/zone.js:371:52)
	    at Zone.run (node_modules/zone.js/fesm2015/zone.js:134:43)
	    at runInTestZone (node_modules/zone.js/fesm2015/zone-testing.js:582:34)
	    at UserContext.<anonymous> (node_modules/zone.js/fesm2015/zone-testing.js:597:20)
	    at <Jasmine>

[BUG] - Events are not tracked using Angular Material - Autocomplete & mat-option

Description/Screenshot
I've got a couple of mat-option from Angular Material in a mat-autocomplete and would like to track when an event is selected. Unfortunately, this does not happen.
It works fine on other elements, like buttons.

Steps to Reproduce

<mat-autocomplete #auto="matAutocomplete">
  <mat-option *ngFor="let option of options" [value]="option" data-test-id="option">
    {{option}}
  </mat-option>
</mat-autocomplete>

Expected behavior
An event with name "option" is being tracked.

Wanting to contribute

Hi, I'm currently preparing an upgrade from an Angular project from Angular v11 to Angular v12.
The project has a dependency on this library, but due to the listed peerDependencies we're obligated to use the --force flag (duplicate of #28). While this works, it's not ideal and it might cause some problems with developers that are not so familiar with it.

I can create a PR with a fix, but I also noticed a few other things that could be approved, hence this issue.
If it's OK, I can create separate PRs for of the following items if you agree:

  • chore: update the dependencies of this lib (this also includes Angular and TypeScript) - reason: running npm install of this repo results in unmet karma dependencies
  • ci: enable the test task during ci - reason: it's currently commented
  • fix: update the peerDependencies to make it compatible with Angular v11 and v12
  • chore: replace TSLint with ESLint - reason: TSLint is deprecated

[BUG] Angular app does not appear in AppInsights Application map

We have an Angular app that interacts with one (or more) .NET Core APIs. We've added the ApplicationInsights JS library to our Angular application, as well as the .NET Core apps.

In Azure Application Insights, we can correctly see the page views for the Angular app, and we can see the API calls being made in the .NET Core app (with all that logging).

But, in the Application Map, I can only see the API portion, and the items it interacts with ie [ API ] ==> [ Storage ], when I expected to be able to see [ App ] ==> [ API ] ==> [ Storage ]. Ideally, we'd be able to see that "user went to /history, which then triggered these three (3) calls, and these 25 interactions with external dependencies.

We are initializing the ApplicationInsights object using:

    config: {
      instrumentationKey: environment.appInsights.instrumentationKey,
      distributedTracingMode: DistributedTracingModes.W3C,
      autoTrackPageVisitTime: true,
      enableAutoRouteTracking: true,
      enableAjaxErrorStatusText: true
    }

and then .startTrackPage and .stopTrackPage.

Is there anything else that we need to configure to get the full dependency map working in Azure? Or is the Application Map only for server-side components, and not for anything running in the Angular code?

(Apologies if this isn't the correct project to raise the question).

[BUG] Incompatible with Angular Hydration

Description/Screenshot

https://angular.io/guide/hydration

Angular offers a new feature for non-destructive client side rehydration. This allows the SSR to serve the page to the client, and the client to take the DOM and only partially recreate the DOM and listeners based on what Angular automatically to have been changed.

What I found was that ApplicationInsights-JS schedules a timeout that negatively impact Zone.js ability to put the page in a "stable" condition.

With ApplicationInsights and hydration enabled, page-load times averaged > 10 seconds. With it disabled, page loads were much more responsive, averaging less than 5 seconds..

Steps to Reproduce

Create an Angular application. Enable SSR and hydration using the following link as a guide: https://angular.io/guide/hydration

Add ApplicationInsights-JS using this guide : https://learn.microsoft.com/en-us/azure/azure-monitor/app/javascript-framework-extensions?tabs=react

Observe load time difference with ApplicationInsights turned on, vs turned off. There will be, at minimum, a ten second difference in total load times before you get the console message confirming hydration.

  • OS/Browser: Chrome Version 114.0.5735.199
  • SDK Version: ^3.0.0
  • How you initialized the SDK: Through the recommended steps in the guide above

Expected behavior

ApplicationInsights does not create timeouts, or offers the ability to avoid them via config, or uses another method to avoid interrupting Angular's Zone.js.

Additional context
Other steps taken:

  • Attempted reducing "maxBatchInterval" to 10 milliseconds to avoid the wait - this reduced wait times from 15 seconds down to 10.
    • What I found is that in ApplicationInsights-JS/channels/applicationinsights-channel-js/src /Sender.ts on line 1013 a default timeout is created that uses the max value of your batch interval or the retry interval. This will default to the retry interval on init, which is default 10 seconds.
image
  • I attempted cancelling the timeout using flush() and pause() on the sender object, but this did not cancel the init, which zone.js tracks and causes the delay for hydration.
  • Also noticed flush does not actually execute the passed in callback:
image

Repository URL pointing to stale page in another repo

The repository.url property in package.json points to a stale page in another repo. Shouldn't it point to this repo instead?

Also, the repository is missing from the published package on NPM. https://www.npmjs.com/package/@microsoft/applicationinsights-angularplugin-js?activeTab=code

It'd be nice to include it. In our project we have a script that generates a file with licenses with links to their repos. The script is looking for repository.url in package.json for finding the link.

Compatibility with Angular 7

Hi,

I have an app in Angular v7.2.16. I am using

"@microsoft/applicationinsights-angularplugin-js": "^2.7.0", 
"@microsoft/applicationinsights-web": "^2.7.2",

I am getting this warning when building
image

And this error when accessing the app
image

I see the compatibility-matrix starts at Angular v11. I am wondering if these are compatibility issues. If so, what versions of AI and the angular plugin should I use for Angular 7?

This is package.json. Please let me know if you need more information. Thank you.

"dependencies": {
    "@angular-devkit/build-angular": "^0.13.0",
    "@angular/animations": "^7.2.16",
    "@angular/cdk": "^7.3.7",
    "@angular/common": "^7.2.16",
    "@angular/compiler": "^7.2.16",
    "@angular/core": "^7.2.16",
    "@angular/forms": "^7.2.16",
    "@angular/material": "^7.3.7",
    "@angular/platform-browser": "^7.2.16",
    "@angular/platform-browser-dynamic": "^7.2.16",
    "@angular/router": "^7.2.16",
    "@microsoft/applicationinsights-angularplugin-js": "^2.7.0",
    "@microsoft/applicationinsights-web": "^2.7.2",
    "angular-gtag": "^1.0.4",
    "animate.css": "^3.7.2",
    "bootstrap": "^4.5.2",
    "core-js": "^2.6.11",
    "hammerjs": "^2.0.8",
    "jquery": "^3.5.1",
    "malihu-custom-scrollbar-plugin": "^3.1.5",
    "ngx-cookie-service": "^2.4.0",
    "ngx-scrollbar": "^4.2.0",
    "popper.js": "^1.16.1",
    "rxjs": "~6.3.3",
    "sweetalert2": "^8.19.0",
    "tableau-api": "^2.2.3",
    "tslib": "^1.13.0",
    "zone.js": "~0.8.26"
  },
  "devDependencies": {
    "@angular/cli": "^7.3.10",
    "@angular/compiler-cli": "^7.2.16",
    "@angular/language-service": "^7.2.16",
    "@types/jasmine": "^2.8.17",
    "@types/jasminewd2": "^2.0.8",
    "@types/node": "~8.9.4",
    "codelyzer": "~4.5.0",
    "jasmine-core": "~2.99.1",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.0.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "^2.1.1",
    "karma-jasmine": "~1.1.2",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "^5.4.4",
    "ts-node": "~7.0.0",
    "tslint": "~5.11.0",
    "typescript": "~3.2.2"
  }

Type 'AngularPlugin' is not assignable to type 'ITelemetryPlugin', Angular 15 ( "@angular/common": "15.1.0") error when trying to build the project

error TS2322: Type 'AngularPlugin' is not assignable to type 'ITelemetryPlugin'.
Types of property 'setNextPlugin' are incompatible.

import { AngularPlugin } from '@microsoft/applicationinsights-angularplugin-js';

    const angularPlugin = new AngularPlugin();
    this.appInsights = new ApplicationInsights({
        config: {
            instrumentationKey: 'key',
            enableAutoRouteTracking: false, // option to log all route changes
            enableCorsCorrelation: true,
            extensions: [angularPlugin],
            extensionConfig: {
                [angularPlugin.identifier]: { router: this.router },
            },
        },
    });
    this.appInsights.loadAppInsights();

extensions: [angularPlugin],
                            ~~~~~~~~~~~~~

"@microsoft/applicationinsights-angularplugin-js": "3.0.1",
"@microsoft/applicationinsights-web": "2.8.9",
"@angular/common": "15.1.0",
"typescript": "4.9.4",

How to log to application insights from a component

I like to log an error from an component. In the readme I find no explanation how I the application insights instance should accessed inside a angular component. Is there a documentation on this that I missed?

Types incompatibility with `@microsoft/applicationinsights-web`

I have an Angular project with

// package.json
"@microsoft/applicationinsights-angularplugin-js": "3.0.0",
"@microsoft/applicationinsights-web": "2.8.6",

If I update @microsoft/applicationinsights-web package to v2.8.7, I get an error

Type 'AngularPlugin' is not assignable to type 'ITelemetryPlugin'.
  Types of property 'setNextPlugin' are incompatible.
...

image

It seems that's because @microsoft/applicationinsights-web depends on @microsoft/[email protected] released 15 days ago, whereas @microsoft/[email protected] depends on @microsoft/applicationinsights-core-js@^2.8.5.

So given that both @microsoft/applicationinsights-angularplugin-js and @microsoft/applicationinsights-web we added to a project before the release of @microsoft/[email protected], @microsoft/applicationinsights-angularplugin-js will continue to depend on @microsoft/[email protected] (last version before 2.8.7), whereas @microsoft/[email protected] will get a @microsoft/[email protected] version, thus resulting in types incompatibility.

Possible solutions

  1. Release a new version of @microsoft/applicationinsights-angularplugin-js that depends on @microsoft/[email protected]. This will make @microsoft/applicationinsights-angularplugin-js and @microsoft/applicationinsights-web use the same version of @microsoft/applicationinsights-core-js
  2. A manual yarn upgrade @microsoft/applicationinsights-angularplugin-js on my side. This was less obvious but apparently running the command results in Yarn updating the @microsoft/applicationinsights-angularplugin-js's dependencies even though the main package didn't have a new version. Took me some time to figure that out.

For now I used solution 2 but solution 1 should be made possible as well.

pageView always the same time

I'm using latest versions for application insights and angular plugin in an angular SPA website:
image

I've created a service and initialized it in the app.component.ts and it's sending the data to the azure application insights. The only thing I'm experiencing is that the time for the pageView in the logs is always the same and it's the one whenever the application it's initialized:

image
image

As you can see in the images the timestamps are grouped for the time the app is initialized, and the only way to get a new timestamp is reloading the app.

For PageVisitTime this is not happening, I get the right time for each call:
image

Is this the intended behaviour or am I doing something wrong?

Thanks in advace.

Unhandled browser exceptions not being tracked in Angular app

Hello,

I am experiencing this issue that was closed/fixed awhile ago: microsoft/ApplicationInsights-JS#282

I created a brand new Angular app using the Angular CLI. Then I made these changes, following this article.

Added a monitoring service:

import {Injectable} from '@angular/core';

import {AppInsights} from 'applicationinsights-js';

@Injectable()
export class MonitoringService {
  private config: Microsoft.ApplicationInsights.IConfig = {
    instrumentationKey: 'KEY_GOES_HERE',
    enableDebug: true,
    verboseLogging: true
  };

  constructor() {
    if (!AppInsights.config) {
      AppInsights.downloadAndSetup(this.config);
    }
  }

  logPageView(name?: string, url?: string, properties?: any, measurements?: any, duration?: number) {
    AppInsights.trackPageView(name, url, properties, measurements, duration);
  }

  logEvent(name: string, properties?: any, measurements?: any) {
    AppInsights.trackEvent(name, properties, measurements);
  }

  trackException(exception: Error) {
    AppInsights.trackException(exception);
  }
}

Added it to my app.component.ts:

import { Component, OnInit } from '@angular/core';
import {MonitoringService} from './monitoring.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [MonitoringService]
})
export class AppComponent implements OnInit {
  title = 'app works!';
  constructor(private monitoringService: MonitoringService) { }

  ngOnInit() {
      this.monitoringService.logPageView();
  }

  throwAnException() {
      this.monitoringService.trackException(new Error('manually track exception'));
      throw 'this should appear in app insights'; // but it doesn't
  }
}

Made a simple button for throwing the exception in my app.component.html:

<h1>
  {{title}}
</h1>
<div (click)="throwAnException()">Click to throw an exception</div>

Logging a page view works, as does tracking the exception by calling trackException. However, I thought all uncaught exceptions would get sent to Application Insights automatically, but I am not seeing any of those show up in the portal. Am I missing something else?

I am using these versions:

applicationinsights-js: 1.0.11
@types/applicationinsights-js: 1.0.4

[Discussion] Re-Numbering the plugin release so the major number matches the Angular release

Hi All,

I want to start a discussion where moving forward I'm thinking that we should change the major version number of this plugin to match the version of Angualur that is targeted (simular to the way the devkit is numbered).

Proposal

  • main: will continue to be the "currently" supported release
  • When we change the targeted verson (in main) of Angular we
    • Update the major version # and reset to 0.0 (so 14.0.0)
    • Create a branch for the previous version (for hotfixes) and active development will generally pause

The main driver of this is that we are already drifting from the previously Application Insights <-> Angular Plugin connection and with the number of versions of breaking changed Angular versions it makes it difficult to understand what / which version should be used.

Because of the size of our team, I don't believe it will be possible to keep all Angular versions up to date with the latest Application Insights versions and while we do support backward compatibility (new versions of Application Insights will load and work with older plugins), this can and has caused TypeScript errors when also including the latest version of Application Insights in your projects during build time.

So while Application Insights v2.8.1 will load and work with any older version of the Angular Plugin (when just injected via the "extensions" config, TypeScript is unhappy with the flexible signature changes that we have introduced to support older and new extension / features. This does seem to depend on your tsconfig.json settings as I don't believe everyone is seeing these issues.

How does this differ from @microsoft/applicationinsights-web?

Pardon my ignorance, but how is this different from @microsoft/applicationinsights-web?

I feel like most people are just going to Google something like "how to use app insights in angular" and end up at this tutorial from Microsoft, which works great.

The only reason I eventually stumbled on this repo was because App Insights was preventing my Angular app from ever becoming stable (ApplicationRef.isStable) and I saw a post somewhere where someone suggested trying this instead. It didn't fix it, and I couldn't really see any immediate differences in logging or anything, either.

Incompatible with @microsoft/applicationinsights-web 2.7.0

after update @microsoft/applicationinsights-web from 2.6.5 to 2.7.0 I get a build error:

Error: src/app/app.component.ts:31:24 - error TS2322: Type 'AngularPlugin' is not assignable to type 'ITelemetryPlugin'.   
  Types of property 'processTelemetry' are incompatible.
    Type '(event: ITelemetryItem, itemCtx?: IProcessTelemetryContext | undefined) => void' is not assignable to type '(env: ITelemetryItem, itemCtx?: IProcessTelemetryContext | undefined) => void'.
      Types of parameters 'itemCtx' and 'itemCtx' are incompatible.
        Type 'import("<sourcefolder>/node_modules/@microsoft/applicationinsights-web/node_modules/@microsoft/applicationinsights-core-js/types/JavaScriptSDK.Interfaces/IProcessTelemetryContext").IProcessTelemetryContext | undefined' is not assignable to type 'import("<sourcefolder>/node_modules/@microsoft/applicationinsights-core-js/types/JavaScriptSDK.Interfaces/IProcessTelemetryContext").IProcessTelemetryContext 
| undefined'.
          Type 'import("<sourcefolder>/node_modules/@microsoft/applicationinsights-web/node_modules/@microsoft/applicationinsights-core-js/types/JavaScriptSDK.Interfaces/IProcessTelemetryContext").IProcessTelemetryContext' is not assignable to type 'import("<sourcefolder>/node_modules/@microsoft/applicationinsights-core-js/types/JavaScriptSDK.Interfaces/IProcessTelemetryContext").IProcessTelemetryContext'.
            The types of 'core().config.extensions' are incompatible between these types.
              Type 'import("<sourcefolder>/node_modules/@microsoft/applicationinsights-web/node_modules/@microsoft/applicationinsights-core-js/types/JavaScriptSDK.Interfaces/ITelemetryPlugin").ITelemetryPlugin[] | undefined' is not assignable to type 'import("<sourcefolder>/node_modules/@microsoft/applicationinsights-core-js/types/JavaScriptSDK.Interfaces/ITelemetryPlugin").ITelemetryPlugin[] | undefined'.
                Type 'import("<sourcefolder>/node_modules/@microsoft/applicationinsights-web/node_modules/@microsoft/applicationinsights-core-js/types/JavaScriptSDK.Interfaces/ITelemetryPlugin").ITelemetryPlugin[]' is not assignable to type 'import("<sourcefolder>/node_modules/@microsoft/applicationinsights-core-js/types/JavaScriptSDK.Interfaces/ITelemetryPlugin").ITelemetryPlugin[]'.
                  Type 'import("<sourcefolder>/node_modules/@microsoft/applicationinsights-web/node_modules/@microsoft/applicationinsights-core-js/types/JavaScriptSDK.Interfaces/ITelemetryPlugin").ITelemetryPlugin' is not assignable to type 'import("<sourcefolder>/node_modules/@microsoft/applicationinsights-core-js/types/JavaScriptSDK.Interfaces/ITelemetryPlugin").ITelemetryPlugin'.
                    Types of property 'processTelemetry' are incompatible.
                      Type '(env: import("<sourcefolder>/node_modules/@microsoft/applicationinsights-web/node_modules/@microsoft/applicationinsights-core-js/types/JavaScriptSDK.Interfaces/ITelemetryItem").ITelemetryItem, itemCtx?: import("<sourcefolder>/node_modules/@mic...' is not assignable to type '(env: import("<sourcefolder>/node_modules/@microsoft/applicationinsights-core-js/types/JavaScriptSDK.Interfaces/ITelemetryItem").ITelemetryItem, itemCtx?: import("<sourcefolder>/node_modules/@microsoft/applicationinsights-core-js/types/JavaScr...'.
                        Types of parameters 'itemCtx' and 'itemCtx' are incompatible.
                          Type 'import("<sourcefolder>/node_modules/@microsoft/applicationinsights-core-js/types/JavaScriptSDK.Interfaces/IProcessTelemetryContext").IProcessTelemetryContext | undefined' is not assignable to type 'import("<sourcefolder>/node_modules/@microsoft/applicationinsights-web/node_modules/@microsoft/applicationinsights-core-js/types/JavaScriptSDK.Interfaces/IProcessTelemetryContext").IProcessTelemetryContext | undefined'.
                            Type 'import("<sourcefolder>/node_modules/@microsoft/applicationinsights-core-js/types/JavaScriptSDK.Interfaces/IProcessTelemetryContext").IProcessTelemetryContext' is not assignable to type 'import("<sourcefolder>/node_modules/@microsoft/applicationinsights-web/node_modules/@microsoft/applicationinsights-core-js/types/JavaScriptSDK.Interfaces/IProcessTelemetryContext").IProcessTelemetryContext'.
                              The types of 'core().config.extensions' are incompatible between these types.
                                Type 'import("<sourcefolder>/node_modules/@microsoft/applicationinsights-core-js/types/JavaScriptSDK.Interfaces/ITelemetryPlugin").ITelemetryPlugin[] | undefined' is not assignable to type 'import("<sourcefolder>/node_modules/@microsoft/applicationinsights-web/node_modules/@microsoft/applicationinsights-core-js/types/JavaScriptSDK.Interfaces/ITelemetryPlugin").ITelemetryPlugin[] | undefined'.
                                  Type 'import("<sourcefolder>/node_modules/@microsoft/applicationinsights-core-js/types/JavaScriptSDK.Interfaces/ITelemetryPlugin").ITelemetryPlugin[]' is not assignable to type 'import("<sourcefolder>/node_modules/@microsoft/applicationinsights-web/node_modules/@microsoft/applicationinsights-core-js/types/JavaScriptSDK.Interfaces/ITelemetryPlugin").ITelemetryPlugin[]'.
                                    Type 'import("<sourcefolder>/node_modules/@microsoft/applicationinsights-core-js/types/JavaScriptSDK.Interfaces/ITelemetryPlugin").ITelemetryPlugin' is not assignable to type 'import("<sourcefolder>/node_modules/@microsoft/applicationinsights-web/node_modules/@microsoft/applicationinsights-core-js/types/JavaScriptSDK.Interfaces/ITelemetryPlugin").ITelemetryPlugin'.
                                      Types of property 'setNextPlugin' are incompatible.
                                        Type '((next: import("<sourcefolder>/node_modules/@microsoft/applicationinsights-core-js/types/JavaScriptSDK.Interfaces/ITelemetryPlugin").ITelemetryPlugin | import("<sourcefolder>/node_modules/@microsoft/applicationinsights-core-js/types/JavaScript...' is not assignable to type '((next: import("<sourcefolder>/node_modules/@microsoft/applicationinsights-web/node_modules/@microsoft/applicationinsights-core-js/types/JavaScriptSDK.Interfaces/ITelemetryPlugin").ITelemetryPlugin | import("<sourcefolder>/node_modules/@micros...'.
                                          Type '(next: import("<sourcefolder>/node_modules/@microsoft/applicationinsights-core-js/types/JavaScriptSDK.Interfaces/ITelemetryPlugin").ITelemetryPlugin | import("<sourcefolder>/node_modules/@microsoft/applicationinsights-core-js/types/JavaScriptS...' is not assignable to type '(next: import("<sourcefolder>/node_modules/@microsoft/applicationinsights-web/node_modules/@microsoft/applicationinsights-core-js/types/JavaScriptSDK.Interfaces/ITelemetryPlugin").ITelemetryPlugin | import("<sourcefolder>/node_modules/@microso...'.
                                            Types of parameters 'next' and 'next' are incompatible.
                                              Type 'import("<sourcefolder>/node_modules/@microsoft/applicationinsights-web/node_modules/@microsoft/applicationinsights-core-js/types/JavaScriptSDK.Interfaces/ITelemetryPlugin").ITelemetryPlugin | import("<sourcefolder>/node_modules/@microsoft/appl...' is not assignable to type 'import("<sourcefolder>/node_modules/@microsoft/applicationinsights-core-js/types/JavaScriptSDK.Interfaces/ITelemetryPlugin").ITelemetryPlugin | import("<sourcefolder>/node_modules/@microsoft/applicationinsights-core-js/types/JavaScriptSDK.Inte...'.
                                                Type 'ITelemetryPlugin' is not assignable to type 'ITelemetryPlugin | ITelemetryPluginChain'.

31           extensions: [angularPlugin],
                          ~~~~~~~~~~~~~

microsoft-applicationinsights-angularplugin-js.mjs error EcmaScript.

Hi,

Angular: 11.2.4
version 2.6.2 also builds without errors. But after the latest version I am getting the following error.

Before : "@microsoft/applicationinsights-angularplugin-js": "^2.6.2",
After : "@microsoft/applicationinsights-angularplugin-js": "2.6.2",

after doing that it was fixed.

ES3 support was removed after version 2.6.3, but I was not getting any errors in the build. I'm getting an error in 2.8.

NOT: I saw that angular 13 support came in version 2.8. Does the problem come from that?

Error: ./node_modules/@microsoft/applicationinsights-angularplugin-js/fesm2015/microsoft-applicationinsights-angularplugin-js.mjs 79:30-49
Can't import the named export 'BaseTelemetryPlugin' from non EcmaScript module (only default export is available)
at HarmonyImportSpecifierDependency._getErrors (/home/vsts/work/1/s/node_modules/webpack/lib/dependencies/HarmonyImportSpecifierDependency.js:88:6)
at HarmonyImportSpecifierDependency.getErrors (/home/vsts/work/1/s/node_modules/webpack/lib/dependencies/HarmonyImportSpecifierDependency.js:68:16)
at Compilation.reportDependencyErrorsAndWarnings (/home/vsts/work/1/s/node_modules/webpack/lib/Compilation.js:1463:22)
at /home/vsts/work/1/s/node_modules/webpack/lib/Compilation.js:1258:10
at _next0 (eval at create (/home/vsts/work/1/s/node_modules/tapable/lib/HookCodeFactory.js:33:10), :41:1)
at eval (eval at create (/home/vsts/work/1/s/node_modules/tapable/lib/HookCodeFactory.js:33:10), :55:1)
at runMicrotasks ()
at processTicksAndRejections (internal/process/task_queues.js:97:5)
@ ./apps/b2b-app/src/app/app.module.ts
@ ./apps/b2b-app/src/main.ts
@ multi ./apps/b2b-app/src/main.ts

Missing Dependency either in package.json or documentation

When following the steps to install/use this plugin, it is stated that i have to use

npm install @microsoft/applicationinsights-angularplugin-js

and later in the 'entry component ' i should add:

import { ApplicationInsights } from '@microsoft/applicationinsights-web';
import { AngularPlugin } from '@microsoft/applicationinsights-angularplugin-js';

But because @microsoft/applicationinsights-angularplugin-js does not have the dependency to @microsoft/applicationinsights-web and it is nowhere noted that you should install @microsoft/applicationinsights-web additionally the rest of the 'Basic Usage' block is not working due to the missing dependency.

So please either add @microsoft/applicationinsights-web as a dependency to @microsoft/applicationinsights-angularplugin-js OR add the additional line npm install @microsoft/applicationinsights-web

Add support for Angular v12

Installing this package on Angular v12, npm throws me this:

PS C:\Users\developer\Documents\a_folder> npm i --save @microsoft/applicationinsights-angularplugin-js 
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: [email protected]
npm ERR! Found: @angular/[email protected]
npm ERR! node_modules/@angular/common
npm ERR!   @angular/common@"~12.0.2" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer @angular/common@"^11.0.6" from @microsoft/[email protected]
npm ERR! node_modules/@microsoft/applicationinsights-angularplugin-js
npm ERR!   @microsoft/applicationinsights-angularplugin-js@"*" from the root project
npm ERR! 
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See C:\Users\developer\AppData\Local\npm-cache\eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\developer\AppData\Local\npm-cache\_logs\2021-06-23T17_38_03_592Z-debug.log

Angular 14 support

When installing on an Angular 14 app I receive a dependency resolution error:

image

v3.0.2 (next: ITelemetryPluginChain | ITelemetryPlugin) => void' is not assignable to type '(next: ITelemetryPlugin | ITelemetryPluginChain) => void'.

similar to #51 , but attempting to use AI 2.8.x, in an Angular 16 project.

When using:

    "@microsoft/applicationinsights-angularplugin-js": "^3.0.2",
    "@microsoft/applicationinsights-web": "^2.8.13",

The errorr is:

Error: src/app/core/services/telemetry.service.ts:37:22 - error TS2322: Type 'AngularPlugin' is not assignable to type 'ITelemetryPlugin'.
  Types of property 'setNextPlugin' are incompatible.
    Type '(next: ITelemetryPluginChain | ITelemetryPlugin) => void' is not assignable to type '(next: ITelemetryPlugin | ITelemetryPluginChain) => void'.
      Types of parameters 'next' and 'next' are incompatible.
        Type 'ITelemetryPlugin | ITelemetryPluginChain' is not assignable to type 'ITelemetryPluginChain | ITelemetryPlugin'.
          Type 'ITelemetryPlugin' is not assignable to type 'ITelemetryPluginChain | ITelemetryPlugin'.
            Type 'import("{projectpath}/node_modules/@microsoft/applicationinsights-core-js/types/applicationinsights-core-js").ITelemetryPlugin' is not assignable to type 'import("{projectpath}/node_modules/@microsoft/applicationinsights-angularplugin-js/node_modules/@microsoft/applicationinsights-core-js/types/JavaScriptSDK.Interfaces/ITelemetryPlugin").ITelemetryPlugin'.
              Types of property 'setNextPlugin' are incompatible.
                Type '(next: ITelemetryPlugin | ITelemetryPluginChain) => void' is not assignable to type '(next: ITelemetryPluginChain | ITelemetryPlugin) => void'.
                  Types of parameters 'next' and 'next' are incompatible.
                    Type 'ITelemetryPluginChain | ITelemetryPlugin' is not assignable to type 'ITelemetryPlugin | ITelemetryPluginChain'.
                      Type 'ITelemetryPluginChain' is not assignable to type 'ITelemetryPlugin | ITelemetryPluginChain'.
                        Type 'import("{projectpath}/node_modules/@microsoft/applicationinsights-angularplugin-js/node_modules/@microsoft/applicationinsights-core-js/types/JavaScriptSDK.Interfaces/ITelemetryPluginChain").ITelemetryPluginChain' is not assignable to type 'import("{projectpath}/node_modules/@microsoft/applicationinsights-core-js/types/applicationinsights-core-js").ITelemetryPluginChain'.
                          The types of 'getPlugin().processTelemetry' are incompatible between these types.
                            Type '(env: import("{projectpath}/node_modules/@microsoft/applicationinsights-angularplugin-js/node_modules/@microsoft/applicationinsights-core-js/types/JavaScriptSDK.Interfaces/ITelemetryItem").ITelemetryItem, itemCtx?: import("{projectpath}/node_modules/@microsoft/applicationinsights-angularplugin-js/n...' is not assignable to type '(env: import("{projectpath}/node_modules/@microsoft/applicationinsights-core-js/types/applicationinsights-core-js").ITelemetryItem, itemCtx?: import("{projectpath}/node_modules/@microsoft/applicationinsights-core-js/types/applicationinsights-core-js").IProcessTelemetryContext) => void'.
                              Types of parameters 'itemCtx' and 'itemCtx' are incompatible.
                                Type 'import("{projectpath}/node_modules/@microsoft/applicationinsights-core-js/types/applicationinsights-core-js").IProcessTelemetryContext' is not assignable to type 'import("{projectpath}/node_modules/@microsoft/applicationinsights-angularplugin-js/node_modules/@microsoft/applicationinsights-core-js/types/JavaScriptSDK.Interfaces/IProcessTelemetryContext").IProcessTelemetryContext'.
                                  Types of property 'createNew' are incompatible.
                                    Type '(plugins?: IPlugin[] | ITelemetryPluginChain, startAt?: IPlugin) => IProcessTelemetryContext' is not assignable to type '(plugins?: ITelemetryPluginChain | IPlugin[], startAt?: IPlugin) => IProcessTelemetryContext'.
                                      Types of parameters 'plugins' and 'plugins' are incompatible.
                                        Type 'ITelemetryPluginChain | IPlugin[]' is not assignable to type 'IPlugin[] | ITelemetryPluginChain'.
                                          Type 'ITelemetryPluginChain' is not assignable to type 'IPlugin[] | ITelemetryPluginChain'.

37         extensions: [angularPlugin],
                        ~~~~~~~~~~~~~

where the TelemtryService I am trying to build (and which worked on Angular v14 project): is:

...
    const angularPlugin = new AngularPlugin();
    this.appInsights = new ApplicationInsights({
      config: {
        connectionString: environment.aiConnStr,
        extensions: [angularPlugin],
        extensionConfig: {
          [angularPlugin.identifier]: {router: this.router },
        },
      },
    });
    this.appInsights.loadAppInsights();
...

Disable logging in local environment

Is there a way to disable logging? I still want to initialize the logging but in my local environment but I don't want it to trigger sending to App Insights.

I tried with:

  • setting instrumentationKey to empty string, but the POST request to App Insigths is always rejected with HTTP status 400 with error message Invalid instrumentation key.
  • setting instrumentationKey to undefined, but I get a runtime error Please provide instrumentation key

I know that it is possible to set a custom endpointUrl as described here but if I set a dummy URL it still tries to send the logs there and I get an error in the browser console.

Thanks

[BUG] Angular 6 | Uncaught RangeError: Maximum call stack size exceeded

Description/Screenshot
I use Angular 6 and I integrated the plugin to my project. All is going well, I receive the errors to App Insight but when my project builds I have all the time this error when app insight is initializing
image

Steps to Reproduce

My package.json :

{
  "name": "tina-web-new",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build --prod",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@agm/core": "^1.0.0-beta.7",
    "@angular/animations": "^6.1.0",
    "@angular/common": "^6.1.0",
    "@angular/compiler": "^6.1.0",
    "@angular/core": "^6.1.0",
    "@angular/forms": "^6.1.0",
    "@angular/http": "^6.1.0",
    "@angular/platform-browser": "^6.1.0",
    "@angular/platform-browser-dynamic": "^6.1.0",
    "@angular/router": "^6.1.0",
    "@microsoft/applicationinsights-angularplugin-js": "^2.5.10",
    "@microsoft/applicationinsights-web": "^2.4.4",
    "@ng-bootstrap/ng-bootstrap": "^3.3.1",
    "@ng-select/ng-select": "^2.12.1",
    "@types/googlemaps": "^3.26.15",
    "auth0-js": "^9.13.4",
    "core-js": "^2.5.4",
    "jquery": "^3.5.1",
    "ngx-bootstrap": "^3.0.1",
    "ngx-image-cropper": "^2.0.2",
    "ngx-pagination": "^5.0.0",
    "ngx-spinner": "^7.0.0",
    "rxjs": "~6.2.0",
    "toastr": "^2.1.4",
    "xlsx": "^0.16.8",
    "zone.js": "~0.8.26"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.8.0",
    "@angular/cli": "~6.2.9",
    "@angular/compiler-cli": "^6.1.0",
    "@angular/language-service": "^6.1.0",
    "@types/jasmine": "~2.8.8",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "~8.9.4",
    "codelyzer": "~4.3.0",
    "jasmine-core": "~2.99.1",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~3.0.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~1.1.2",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.4.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.11.0",
    "typescript": "~2.9.2"
  }
}

My Appcomponent.ts :

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { ApplicationInsights } from '@microsoft/applicationinsights-web';
import { AngularPlugin, AngularPluginService } from '@microsoft/applicationinsights-angularplugin-js';

@Component({
  selector: 'body',
  template: '<ngx-spinner bdColor = "rgba(51, 51, 51, 0.8)" size="medium" color ="#fff" type="ball-spin-fade"></ngx-spinner><router-outlet></router-outlet>',
})
export class AppComponent implements OnInit {
  title = 'TinaWebNew';

  private appInsights;
    constructor(
        private router: Router,
        private angularPluginService: AngularPluginService 
    ){
        var angularPlugin = new AngularPlugin();
        this.angularPluginService.init(angularPlugin, this.router);
        this.appInsights = new ApplicationInsights({ config: {
        instrumentationKey: 'MyKey',
        extensions: [angularPlugin],
        extensionConfig: {
            [angularPlugin.identifier]: { router: this.router }
        },
        } });
    }

    ngOnInit() {
        this.appInsights.loadAppInsights();
    }
} 

Expected behavior

The project builds without errors.

[BUG] Type 'AngularPlugin' is not assignable to type 'ITelemetryPlugin'

Having the following releases configured in the package.json

    "@microsoft/applicationinsights-angularplugin-js": "^2.8.1",
    "@microsoft/applicationinsights-web": "^2.8.0",
    "@microsoft/applicationinsights-angularplugin-js": "^2.8.0",
    "@microsoft/applicationinsights-web": "^2.8.0",

This configuration causes the application insights configuration to fail with the error:

this.applicationInsights = new ApplicationInsights({
      config: {
        enableRequestHeaderTracking: true,
        enableResponseHeaderTracking: true,
        enableCorsCorrelation: true,
        extensions: [this.angularPlugin], // THIS LINE DOESN'T COMPILE WITH BELOW ERROR
      },
    });
Type 'AngularPlugin' is not assignable to type 'ITelemetryPlugin'
Types of property 'setNextPlugin' are incompatible.

I had to fix the appinsights-web version to 2.7.4 to resolve the issue

InstrumentationKey should not be needed if connectionString is already present

I am already providing the connectionString in the config, which I thought it was enough for it to work

image

But the app throws an error expecting the instrumentationKey property also to be added

image

Im using the following versions

    "@microsoft/applicationinsights-angularplugin-js": "^2.9.1",
    "@microsoft/applicationinsights-web": "~2.8.2",

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.