在$stateChangeStart的AngularJS运行函数中未设置异步数据

在$stateChangeStart的AngularJS运行函数中未设置异步数据,angularjs,angular-ui-router,Angularjs,Angular Ui Router,我试图在服务的角度运行函数中设置一个值。 首次加载时未在会话存储中设置该值。 当我第二次重新加载url时,该值将可用。请帮我解决这个问题 appName.run(function($rootScope, $state, $window, testSerivces) { $rootScope.$on("$stateChangeStart", function(event, toState, toParams, fromState, fromParams) { if ($window.s

我试图在服务的角度运行函数中设置一个值。 首次加载时未在会话存储中设置该值。 当我第二次重新加载url时,该值将可用。请帮我解决这个问题

appName.run(function($rootScope, $state, $window, testSerivces) {
  $rootScope.$on("$stateChangeStart", function(event, toState, toParams, fromState, fromParams) {
    if ($window.sessionStorage.getItem('loginID') === null) {
      testSerivces.login().then(function(response) {
        $window.sessionStorage.setItem('loginID', response.data.profile.id);
      }, function(e) {
        console.log(e);
      }).finally(function() {

      });
    }
  });
});
您之所以会看到这种行为,是因为您在调用testSerivces.login时发送了一个异步请求,同时状态更改将继续进行。i、 例如,testSerivces.login在后台发生,而状态更改正在继续传播。因此,您必须停止事件并等待服务解决,然后继续。将代码更改为

appName.run(function($rootScope, $state, $window, testSerivces) {
  $rootScope.$on("$stateChangeStart", function(event, toState, toParams, fromState, fromParams) {
    if ($window.sessionStorage.getItem('loginID') === null) {
        event.preventDefault(); // Prevent Propgation
        testSerivces.login().then(function(response) {
        $window.sessionStorage.setItem('loginID', response.data.profile.id);
        $state.go(toState, toParams); //Start Propogation Again
      }, function(e) {
        console.log(e);
      }).finally(function() {

      });
    }
  });
});

我会成功的。希望这会有所帮助。

为UI路由器添加状态表。另外,您正在使用哪个版本的UI路由?当页面最初加载时是否发出$stateChangeStart?georgeawg@I正在使用angular UI-router@versionv0.4.2.Pytth@$stateChangeStart正在发布感谢Anees的快速回复。该值正在设置中,但我可以看到多个登录服务请求正在发送到服务器。我已修复了多个服务调用问题。这是由于stateRouter的一些错误配置造成的。谢谢你的解决方案