ui-router 为谷歌分析获取状态变化的当前路径路径、状态、ui、router

2023-09-06 14:44:45 作者:梅幽香更远

我正在尝试获取状态路径以发送到谷歌分析.有一些问题.我正在使用抽象状态,所以使用类似 toState.url 的东西不会起作用,因为它不会抓取整个 url.

I am trying to get the path of the state to send to google analytics. There are some issues. I am using abstract states, so using something like toState.url wont work as it wont grab the entire url.

我曾想过在 $stateChangeSuccess 上使用 $window.location.pathname,但结果是在浏览器中更新 url 之前成功触发.这意味着页面浏览量发送 1 个页面浏览量为时已晚.即.

I thought of using $window.location.pathname on $stateChangeSuccess, but it turns out success fires before the url is updated in the browser. This means that pageviews get sent 1 page view too late. ie.

click about: sends nothing
click contact: sends about url
click services: sends contact url

基本上最终结果应该是这样的,但是带有 toState url 或路径名:

Basically the end result should look something like this, but with the toState url or pathname:

$rootScope.$on("$stateChangeStart", function(event, toState, toParams, fromState, fromParams) {
  var path = ???; 
  ga('send', 'pageview', path);
});

推荐答案

看起来你需要使用 $location 来获取新路径:

looks like you need to use $location instead to get the new path:

$rootScope.$on("$stateChangeSuccess", function(event, toState, toParams, fromState, fromParams) {
  $window.ga('send', 'pageview', $location.path());
});