ui-router getting current path on state change for

2019-04-09 05:56发布

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.

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

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);
});

1条回答
唯我独甜
2楼-- · 2019-04-09 06:20

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());
});
查看更多
登录 后发表回答