ui-router-extras icon indicating copy to clipboard operation
ui-router-extras copied to clipboard

Angular ui router (extras) $stateChangeStart event trigger twice

Open vlatkoodrljin opened this issue 9 years ago • 3 comments

Can someone explain me why Angular UI Router Extras addition trigger twice (on init!) $stateChangeStart event in case when i have some async ajax check and e.preventDefault() call?

Short event code example:

  $rootScope.$on("$stateChangeStart", function (e, toState, toParams, fromState, fromParams, error) {
   console.log("$stateChangeStart");//fired twice
   if(!User.data) {
         e.preventDefault();
         $http.get("https://randomuser.me/api/")
         .success(function(data, status, headers, config) {
              console.log(data);
              User.data = data; 
              $state.go(toState, toParams);
          });
   }              
 });

FIDDLE: http://jsfiddle.net/wLcxyxh1/

Without extras addition everything is working as expected.

Tnx

vlatkoodrljin avatar Jul 21 '15 22:07 vlatkoodrljin

Having the same issue here

rysilva avatar Oct 21 '15 16:10 rysilva

Has anyone had any luck finding a workaround for this? I'm having the same issue.

Here's a simplified example: http://codepen.io/chrisguerrero/pen/beBXjV

chrisguerrero avatar Jun 23 '16 17:06 chrisguerrero

@chrisguerrero that's happening because of Future States retrying the initial transition. Future states resyncs the URL after all the async state loading is complete. It does this in case the URL that was originally requested was for a state that wasn't loaded yet.

The reason your pen is triggering this behavior is that your $stateChangeStart handler is cancelling the initial transition. Normally, the transition would complete, the URL would be updated, and then the handler would re-sync() the url. But, since the url matches the state already, the second sync() is normally a no-op.

https://github.com/christopherthielen/ui-router-extras/blob/0.1.2/src/future.js#L261-L272


The workaround here is if you're not using Future States is to use the modular build of ui-router-extras and not pull in Future States.

christopherthielen avatar Jun 23 '16 17:06 christopherthielen