AngularJS Amplitude Service Not Acting as Singleton

心不动则不痛 提交于 2019-12-11 05:08:31

问题


I have recently posted a similar question, but this is not a duplicate. Apologies for the code heavy post but I wanted to provide as much context as possible. I am having an issue with defining the analytics tool, 'Amplitude' as a service in my Angular.js application. Services are supposed to act as singletons throughout an application (source), so I am confused to be getting the following behavior.

In my app.js file, I call AmplitudeService.logEvent('EVENT_NAME') in a .run function which successfully logs the event to Amplitude. Note: Console.log(AmplitudeService) returns an object with all the correct functions here.

However, when I call AmplitudeService.logEvent('EVENT_NAME') within any other controller, such as header.js I do not ever see any data in my Amplitude dashboard. Note: Console.log(AmplitudeService) returns an identical object within header.js to the one returned from app.js

Would appreciate any and all insight!

P.S. The official AmplitudeJS SDK is here. I am trying to implement it through this wrapper.

AmplitudeService.js (source)

Note: If you check the author's syntax, he returns an object at the end of his service. In my research, I've read to use the "this" keyword when defining Service functions (source), and that you don't need to return an object as you would with a Factory, so I have updated it accordingly.

angular.module('AmplitudeService', [])
.service('AmplitudeService', 
['$amplitude', '$rootScope', 'amplitudeApiKey', '$location',
function ($amplitude, $rootScope, amplitudeApiKey, $location) {

  this.init = function() {
    $amplitude.init(amplitudeApiKey, null);
  }

  this.identifyUser = function(userId, userProperties) {
    $amplitude.setUserId(userId);
    $amplitude.setUserProperties(userProperties);
  }

  this.logEvent = function(eventName, params) {
    $amplitude.logEvent(eventName, params);
  }
}]);

angular-amplitude.js (source)

This allows access to "$amplitude" throughout the application

(function(){
var module = angular.module('angular-amplitude', ['ng']);

module.provider('$amplitude', [function $amplitudeProvider() {
this.$get = ['$window', function($window) {
  (function(e,t){
    var r = e.amplitude || {};
    var n = t.createElement("script");
    n.type = "text/javascript";
  n.async = true;
  n.src = "https://d24n15hnbwhuhn.buttfront.net/libs/amplitude-2.2.0-min.gz.js";
  var s = t.getElementsByTagName("script")[0];
  s.parentNode.insertBefore(n,s);
  r._q = [];

  function a(e){
    r[e] = function(){
      r._q.push([e].concat(Array.prototype.slice.call(arguments,0)));
    }
  }
  var i =    ["init","logEvent","logRevenue","setUserId","setUserProperties","setOptOut","setVersionName","setDomain","setDeviceId","setGlobalUserProperties"];
  for(var o = 0; o < i.length; o++){
    a(i[o])
  }
  e.amplitude = r
}
  )(window,document);
  return $window.amplitude;
}];
}]);
return module;
}());

App.js

angular.module('app', [
'ngRoute',
'angular-amplitude',
'AmplitudeService',
])

 .run(['AmplitudeService', function(AmplitudeService){
 console.log(AmplitudeService); // Outputs 'Object {}'
 AmplitudeService.init();
 *AmplitudeService.logEvent('LAUNCHED_SITE'); // This logs the event*
 console.log(AmplitudeService); // Outputs 'Object {}'
 }])

Header.js

  angular.module('app.common.header', [])
 .controller('HeaderCtrl', [ '$rootScope', '$scope', '$location','$route', '$window', 'AmplitudeService', function($rootScope, $scope, $location, $route, $window, AmplitudeService){

 $scope.goToSearch = function(term) {
 $location.path('/search/' + term);
  console.log(AmplitudeService); // Outputs 'Object {}'
*AmplitudeService.logEvent('SEARCHED');* // This does not log the event
 };
 }]);

Update: I have tried switching the Service to a Factory and that did not generate any new results.


回答1:


Found the solution and hope this is helpful to anyone that comes across this. My solution was to initialize the SDK by calling AmplitudeService.init() within a .run() function within app.js, which initialized an amplitude object within my window. From there forward, I included $window as a service in each of my controllers and called $window.amplitude.logEvent('event_name_here');

Feel free to contact if you have questions. Thanks.




回答2:


We had similar issues on a large project and we created a wrapper providing a directive to init Amplitude and a service to provide the logEvent and sendUserId.



来源:https://stackoverflow.com/questions/37421245/angularjs-amplitude-service-not-acting-as-singleton

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!