道歉的代碼沉重的職位,但我想提供儘可能多的上下文儘可能。我在我的Angular.js應用程序中定義服務時遇到問題。服務應該在整個應用程序中扮演單身人士(source),所以我很困惑會得到以下行爲。AngularJS服務不作爲單身人士
在我app.js文件,我跑我AmplitudeService服務和執行console.log(AmplitudeService)。這將輸出一個包含我在AmplitudeService.js文件中定義的所有方法的對象。因此,我能夠按預期正確使用服務和記錄事件。
但是,當我在我的header.js內的console.log(AmplitudeService)時,它輸出我的Window對象。因此,該窗口不包含諸如「logEvent」,「identifyUser」等功能,所以AmplitudeService在這種情況下不可用。
希望任何和所有的見解!
AmplitudeService.js(source)
注:如果您選中了作者的語法,他在他的服務端返回一個對象。在我的研究中,我已經讀過在定義服務功能(source)時使用「this」關鍵字,並且您不需要象Factory一樣返回對象,所以我已經相應地更新了它。
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);
}
}]);
角amplitude.js(source)
這允許整個應用程序
(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');
console.log(AmplitudeService); // Outputs 'Object {}'
}])
Header.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 {}'
};
}]);
我想我需要$範圍,但我可能是錯的。我在Header.js中的所有函數(我已經減少了這篇文章中的代碼量)被列爲$ scope函數。例如,$ scope.goToSearch(term)將進入我的搜索頁面並搜索該術語。這個函數在HTML中使用ng-submit =「goToSearch(term)」來調用。 – zomp
我已經刪除了$ scope注入,但現在我在該控制器中有7個未定義的函數。還有其他建議嗎?我很欣賞以前的評論。 – zomp
你已經注入了'$ scope'兩次 - 在你的例子(第一個代碼示例)中看看我已經添加了'**'$ scope'**'。刪除這個定義,你應該很好去。 –