Giter Site home page Giter Site logo

johnhidey / angular-appinsights Goto Github PK

View Code? Open in Web Editor NEW
49.0 8.0 17.0 29 KB

An Angular module for using Microsoft's Application Insights within a SPA

License: MIT License

JavaScript 100.00%
angular microsoft-application-insights spa application-insights angular-appinsights

angular-appinsights's Introduction

Stories in Ready Stories in Progress Known Vulnerabilities

Angular-AppInsights

Angular-AppInsights is an angular module for using Microsoft's Application Insights within a SPA (Single Page Application).

Usage

Get your regular Microsoft's Application Insights

<!--
To collect end-user usage analytics about your application,
insert the following script into each page you want to track.
Place this code immediately before the closing </head> tag,
and before any other scripts. Your first data will appear
automatically in just a few seconds.
-->
<script type="text/javascript">
    var appInsights=window.appInsights||function(config){
    function i(config){t[config]=function(){var i=arguments;t.queue.push(function(){t[config].apply(t,i)})}}var t={config:config},u=document,e=window,o='script',s='AuthenticatedUserContext',h='start',c='stop',l='Track',a=l+'Event',v=l+'Page',y=u.createElement(o),r,f;y.src=config.url||'https://az416426.vo.msecnd.net/scripts/a/ai.0.js';u.getElementsByTagName(o)[0].parentNode.appendChild(y);try{t.cookie=u.cookie}catch(p){}for(t.queue=[],t.version='1.0',r=['Event','Exception','Metric','PageView','Trace','Dependency'];r.length;)i('track'+r.pop());return i('set'+s),i('clear'+s),i(h+a),i(c+a),i(h+v),i(c+v),i('flush'),config.disableExceptionTracking||(r='onerror',i('_'+r),f=e[r],e[r]=function(config,i,u,e,o){var s=f&&f(config,i,u,e,o);return s!==!0&&t['_'+r](config,i,u,e,o),s}),t
    }({
        instrumentationKey:"your key here"//<-- optionally remove this to apply in 'start'. See 'Note' below
    });
    
    window.appInsights=appInsights;
    appInsights.trackPageView(); //<-- remove this
</script>

You tag should look like this when modified:

<!--
To collect end-user usage analytics about your application,
insert the following script into each page you want to track.
Place this code immediately before the closing </head> tag,
and before any other scripts. Your first data will appear
automatically in just a few seconds.
-->
<script type="text/javascript">
    var appInsights=window.appInsights||function(config){
    function i(config){t[config]=function(){var i=arguments;t.queue.push(function(){t[config].apply(t,i)})}}var t={config:config},u=document,e=window,o='script',s='AuthenticatedUserContext',h='start',c='stop',l='Track',a=l+'Event',v=l+'Page',y=u.createElement(o),r,f;y.src=config.url||'https://az416426.vo.msecnd.net/scripts/a/ai.0.js';u.getElementsByTagName(o)[0].parentNode.appendChild(y);try{t.cookie=u.cookie}catch(p){}for(t.queue=[],t.version='1.0',r=['Event','Exception','Metric','PageView','Trace','Dependency'];r.length;)i('track'+r.pop());return i('set'+s),i('clear'+s),i(h+a),i(c+a),i(h+v),i(c+v),i('flush'),config.disableExceptionTracking||(r='onerror',i('_'+r),f=e[r],e[r]=function(config,i,u,e,o){var s=f&&f(config,i,u,e,o);return s!==!0&&t['_'+r](config,i,u,e,o),s}),t
    }({});
    window.appInsights=appInsights;
</script>

Note: You can apply other settings here for application insights if you choose. See the Microsoft documentation for IConfig for possible parameters.

Include the following script tag

<script type="text/javascript" src="angular-appinsights.js"></script>

on your SPA shell page (perferrably at the bottom of the <body>). Now all we need to do is initialize the angular-appinsights module and we're done. The best place to initialize angular-appinsights is in your application bootstrap. Below is sample of what this might look like. Make sure to take note that the application now has a dependency on angular-appinsights.

angular.module('insightsApp', ['ngRoute', 'angular-appinsights'])
    .config(['$routeProvider', 'insightsProvider', function ($routeProvider, insightsProvider) {

        $routeProvider
            .when('/', {
                templateUrl: "page1.html",
                controller: 'page1Controller'
            })
            .when('/page2', {
                templateUrl: "page2.html"
            });

        // Add application insights id here
        insightsProvider.start('Application Insights Application Id');
    }])

You angular application will now log all page views defined by subscribing to the event locationChangeSuccess within angular. You're up and logging page views now.

To log custom events you just need to have a dependency on insights and Angular's DI will deliver you the object. From there it is pretty simple. You will call insights.logEvent() passing your event data. For a complete definition of the method please refer to Microsoft's document on logEvent. You can also log page views by calling insights.logPageView(). For a complete definition of the method please refer to Microsoft's document on logPageView. Below is a sample where the page1Controller is logging it's activation.

angular.module('insightsApp', ['ngRoute', 'angular-appinsights'])
    .config(['$routeProvider', 'insightsProvider', function ($routeProvider, insightsProvider) {

        $routeProvider
            .when('/', {
                templateUrl: "page1.html",
                controller: 'page1Controller'
            })
            .when('/page2', {
                templateUrl: "page2.html"
            });

        // Add application insights id here
        insightsProvider.start('Application Insights Application Id');

    }])
    .controller('page1Controller', ['$scope', 'insights', function($scope, insights) {

        insights.logEvent('Page 1 Controller Activated');

    }]);

API

start(appId, appName)

Initializes the Application Insights object with default settings using the provided appId and optional appName.

  • appId (string) - The key of your Application Insights resource in Azure.
  • appName (string) - Optional. Text that is prepended to the path information when the angular page is changed. Default: (Application Root)

Example

insightsProvider.start('00000000-0000-0000-0000-000000000000', 'MyApp');

start(options)

Initializes the Application Insights object with settings applied from an options object.

Example

var options = {
    appId: '00000000-0000-0000-0000-000000000000',
    appName: 'MyApp'
};
insightsProvider.start(options);

##Change Log Please see CHANGELOG.md

##License MIT. Please see LICENSE

angular-appinsights's People

Contributors

davidhoerster avatar dennismi avatar johnhidey avatar jt000 avatar michelsmit avatar raphaelsk avatar simonua avatar waffle-iron 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  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

angular-appinsights's Issues

insights.logEvent is not a function

Just installed version 0.0.4 and we are getting this message whenever we try to log an error. I looked through the new version and didn't see a trace of logEvent.

Your readme is still referring to logEvent.

Package disappeared from npm

Starting from yesterday (I think) it's impossible to install the package with npm. This breaks all of our existing CI pipelines

Failed to initialize AppInsights JS SDK: Cannot load Application Insights SDK, no instrumentationKey was provided

Upon suggestion in the sample, I still continuously get this error, because I defer sending the key until

.config(['$stateProvider', '$urlRouterProvider' , 'insightsProvider', ($stateProvider, $urlRouterProvider, insightsProvider) => {
...
        insightsProvider.start('12345', 'MyApp');
    }])

and more importantly, the tracking is not working.
Is there some sort of option that can be sent in the initial script to fix this ?

Thanks

TypeError: appInsights.start is not a function

Hi,

I have followed the instructions (3 times ;) and keep getting this error onload: "TypeError: appInsights.start is not a function"

It's happening on this line of code:

            if (appInsights && appId) {
                appInsights.start(appId);
            }

is this library still functional?

Missing something in the setup procedure

Hi

Just tried to use your wonderfull angular module. I followed your instructions in the readme.md file, but it kept failing with appInsights being undefined. (I installed it via nuget)

after trying the official MS tag i got start is an undefined function.

Then i dug around in your test pages, and found that you included the appInsights.js file, which creates an appInsights object, which it can use.

After i added that piece of code, it all worked.

I'm not sure wether or not the MS script has changed since you published the nuget file or created this project.

Either way, just wanted to let you know :)

//dennismi

TypeError: insights.startTrackPage is not a function

This error is occurring for me on https://github.com/johnhidey/angular-appinsights/blob/master/lib/angular-appinsights.js#L76 on first time page load:

TypeError: insights.startTrackPage is not a function

Seems to be related to this StackOverflow post, suggesting:

The reason is that startTrackPage() method is only defined in the JS that is downloaded from CDN, so until it is downloaded it is not defined.

I'm using the Microsoft-provided snippet to load the app insights SDK from their CDN.

Error: [$injector:modulerr] Failed to instantiate module shared due to: TypeError: appInsights.start is not a function at Object.start (http://localhost/Scripts/angular-appinsights.js:20:33)

Failing to start the module,

TypeError: appInsights.start is not a function
at Object.start (http://localhost/Scripts/angular-appinsights.js:20:33)

shared.config(['$stateProvider', '$httpProvider', 'insightsProvider', function ($stateProvider, $httpProvider, insightsProvider) {
$stateProvider
.state('preview', {
url: '/preview/:id',
controller: "previewController as preview",
templateUrl: 'app/shared/preview/preview.html'
});
insightsProvider.start('key');

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.