我正在尝试将 Google Analytics 添加到我的网络SPA应用中。我已将GA脚本添加到index.html
文件中:
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-XXXXXXXX-1', 'auto');
</script>
这是我的"$stateChangeSuccess"
事件:
$rootScope.$on("$stateChangeSuccess", function(event, toState, toParams, fromState, fromParams){
var url = API_URL+$location.url()
console.log(url)
$window.ga('send', 'pageview', { page: url }); // line 54
});
这是我得到的:
>>http://localhost:3030/search
>>angular.js:9959 TypeError: undefined is not a function
at app.run.js:54
at Scope.$get.Scope.$broadcast (angular.js:12874)
at $state.transitionTo.$state.transition.resolved.then.$state.transition (angular-ui-router.js:3218)
at deferred.promise.then.wrappedCallback (angular.js:11485)
at angular.js:11571
at Scope.$get.Scope.$eval (angular.js:12595)
at Scope.$get.Scope.$digest (angular.js:12407)
at Scope.$get.Scope.$apply (angular.js:12699)
at done (angular.js:8287)
at completeRequest (angular.js:8499)
从这个错误中我可以得到$window.ga()
是undefined
我做错了什么以及如何让它发挥作用?
答案 0 :(得分:0)
你确定var url = API_URL+$location.url()
这条线路运行良好吗?
您初始化API_URL
?
以及您初始化$location
的位置?
因此,API_URL
和$location
可能会收到该错误。(但不确定)
因此,您需要声明API_URL
值并在$scope.$on
事件中注入该位置。
您的代码应为
$rootScope.$on("$stateChangeSuccess", function($location){
var API_URL ="Your Url";//Put your url
var url = API_URL + $location.url();
console.log(url);
$window.ga('send', 'pageview', { page: url }); // line 54
});
尝试以下代码
您错过了初始化$ window
$rootScope.$on("$stateChangeSuccess", function($location, $window){
var API_URL = "Your Url"; // Put your url
var url = API_URL + $location.url();
console.log(url);
$window.ga('send', 'pageview', { page: url }); // line 54
});