为代码繁重的帖子道歉,但我想提供尽可能多的上下文。我在 Angular.js 应用程序中定义服务时遇到问题。服务应该在整个应用程序(源)中充当单例,所以我很困惑得到以下行为。
在我的app.js文件中,我运行我的AmplitudeService服务和 console.log(AmplitudeService)。这将输出一个包含我在 AmplitudeService.js 文件中定义的所有方法的对象。因此,我能够按预期正确使用服务和记录事件。
但是,当我在header.js中使用 console.log(AmplitudeService) 时,它会输出我的 Window 对象。因此,Window 不包含“logEvent”、“identifyUser”等函数,因此在这种情况下, AmplitudeService不可用。
将不胜感激任何和所有的见解!
AmplitudeService.js (来源)
注意:如果您检查作者的语法,他会在服务结束时返回一个对象。在我的研究中,我读过在定义服务函数(source)时使用“this”关键字,并且您不需要像使用工厂那样返回对象,因此我已相应地对其进行了更新。
angular.module('AmplitudeService', [])
.service('AmplitudeService',
['$amplitude', '$rootScope', 'amplitudeApiKey', '$location',
function ($amplitude, $rootScope, amplitudeApiKey, $location) {
this.init = function() {
$amplitude.init(amplitudeApiKey, null);
$amplitude.logEvent('LAUNCHED_SITE', {page: $location.$$path});
}
this.identifyUser = function(userId, userProperties) {
$amplitude.setUserId(userId);
$amplitude.setUserProperties(userProperties);
}
this.logEvent = function(eventName, params) {
$amplitude.logEvent(eventName, params);
}
}]);
angular-amplitude.js (来源)
这允许在整个应用程序中访问“$amplitude”
(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;
}());
应用程序.js
angular.module('app', [
'ngRoute',
'angular-amplitude',
'AmplitudeService',
])
.run(['AmplitudeService', function(AmplitudeService){
console.log(AmplitudeService); // Outputs 'Object {}'
AmplitudeService.init();
AmplitudeService.logEvent('LAUNCHED_SITE');
console.log(AmplitudeService); // Outputs 'Object {}'
}])
页眉.js
angular.module('app.common.header', [])
.controller('HeaderCtrl', [ '$rootScope', '$scope', '$location', '$scope', '$route', '$window', 'AmplitudeService', function($rootScope, $scope, $location, $route, $window, AmplitudeService){
$scope.goToSearch = function(term) {
$location.path('/search/' + term);
console.log(AmplitudeService); // Outputs 'Window {}'
};
}]);