使用ui-router(AngularJS)时,$ rootScope.$ on("$ routeChangeSuccess)或$ rootScope.$ on(" $ stateChangeSuccess)不起作用 [英] $rootScope.$on("$routeChangeSuccess) or $rootScope.$on("$stateChangeSuccess) does not work when using ui-router(AngularJS)

查看:77
本文介绍了使用ui-router(AngularJS)时,$ rootScope.$ on("$ routeChangeSuccess)或$ rootScope.$ on(" $ stateChangeSuccess)不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在应用程序中使用UI-router进行嵌套视图,但同时我想在路由更改时侦听事件.在使用UI路由器之前,routeChangeSuccess可以很好地触发,但是在ui-router之后,它不会触发.文档建议使用viewContedLoaded或stateChangeSuccess来使用,但即使它们不会被解雇.我正在粘贴我的代码片段. 任何帮助将不胜感激.

I am using UI-router for nested views in my application but at the sametime I want to listen for events when the route changes. Before using UI-router routeChangeSuccess was firing just fine but after ui-router it does not fire. Documentation suggests to use viewContedLoaded or stateChangeSuccess to be used but even they dont get fired. I am pasting my code snippet. Any help would be appreciated.

var app = angular.module('SmartKart', ['ngCookies','ngRoute','ui.bootstrap','angularPayments','ngAnimate','toaster','ui.router','LocalStorageModule']);
app.config(['$routeProvider','$httpProvider','$urlRouterProvider', '$stateProvider',  function($routeProvider, $httpProvider,$urlRouterProvider,$stateProvider) {
$routeProvider
//TODO: Clean-up...most of these routes can be eliminated since we are now using nested views inside main.html. should probably use .otherwise(... main.html) or something
  .when('/postal',
  {
    templateUrl: 'static/partials/landingPage.html',
    requireLogin: false
  })
  .when('/register',
  {
    templateUrl:'static/partials/landingPage.html',
    requireLogin: false
  })
  .when('/login',
  {
    templateUrl:'static/partials/landingPage.html',
    requireLogin: false
  })
  .when('/forgot',
  {
    templateUrl:'static/partials/landingPage.html',
    requireLogin: false
  })
  //TODO: Clean-up...most of these routes can be eliminated since we are now using nested views inside main.html
  .when('/noregister',
  {
    templateUrl:'static/partials/landingPage.html',
    requireLogin: false
  })
  .when('/contact',
  {
    templateUrl:'static/partials/contact.html'
  })
  .when('/home',
  {
    templateUrl:'static/partials/main.html',
    requireLogin: true
  })
  .when('/productList', //so routeProvider will load main.html, stateProvider will load the product list nested view
  {
    templateUrl:'static/partials/main.html',
    requireLogin: true
  })
  .when('/searchResults', //so routeProvider will load main.html, stateProvider will load the product list nested view
  {
    templateUrl:'static/partials/main.html',
    requireLogin: true
  })
  .when('/products/:storeId',
  {
    templateUrl:'static/partials/main.html',
    requireLogin: true    
  })
  .when('/products/store/:storeId/department/:departmentId/aisle/:aisleId',
  {
    templateUrl:'static/partials/main.html',
    requireLogin: true    
  })
  // .when('/productDetail/:productId',
  // {
  //   templateUrl:'static/partials/productDetail.html' ,
  //   requireLogin: true
  // })
  .when('/checkout',{
    templateUrl:'static/partials/page.html',
    requireLogin: true
  })
  .when('/jobrequest',{
    templateUrl:'static/partials/driverJobRequest.html'
  })
  .when('/orders',{
    templateUrl:'static/partials/page.html', //stateProvider will load the Orders list as a nested view within the main html
    requireLogin: true
  })
  .when('/admin',{
    templateUrl:'static/partials/main.html'
  })
  .when('/reset',{
    templateUrl:'static/partials/resetPassword.html'
  })
  .when('/changePassword',{
    templateUrl:'static/partials/changePassword.html',
    requireLogin: false
  })
  .when('/driver/:orderNumber',{
    templateUrl:'static/partials/main.html',
    requireLogin: false
  })
  .when('/driver',{
    templateUrl:'static/partials/main.html',
    requireLogin: false
  })
  .when('/profilepage',{
    templateUrl:'static/partials/profilePage.html',
    requireLogin: false
  })
  .when('/', {
    templateUrl : 'static/partials/landingPage.html', 
    requireLogin: false
  });

   $httpProvider.defaults.useXDomain = true;
   delete $httpProvider.defaults.headers.common['X-Requested-With'];
   $httpProvider.defaults.withCredentials = true;

  //Used for controlling nested views inside main.html and page.html
  $stateProvider 
    .state('products', {
        url: "/productList",
        templateUrl: "static/partials/productList.html",
        controller: 'ProductListCtrl'
    })
    .state('searchResults', {
        url: "/searchResults",
        templateUrl: "static/partials/searchResults.html",
        controller: 'ProductSearchResultsCtrl'
    })
    .state('orders', {
        url: "/orders",
        templateUrl: "static/partials/orderList.html",
        controller: 'UserOrderListCtrl'

    })        
    .state('checkout', {
        url: "/checkout",
        templateUrl: "static/partials/checkout.html",
        controller: 'checkoutCtrl'
    })

    .state('admin', {
        url: "/admin",
        templateUrl: "static/partials/admin.html",
        controller: 'AdminCtrl'
    })
    .state('driver', {
        url: "/driver",
        templateUrl: "static/partials/driverDashboard.html",
        controller: 'DriverDashboardCtrl'
    })
    .state('driverOrder', { //gets assigned order for this number
        url: "/driver/:orderNumber",
        templateUrl: "static/partials/singleOrder.html",
        controller: 'OrderCtrl',
        resolve: {
          order: function($stateParams) {
          return $stateParams.orderNumber;
             }
         }
    });

  }]);


app.run(['$rootScope', '$location' ,'$cookieStore', '$state', 'CacheManager',  function($rootScope, $location, $cookieStore, $state,CacheManager){

 //(re)load cached values here
 //CacheManager.loadCache();

 $rootScope.$on(['stateChangeStart', function(){
 alert('hello1');
 var urlCheck1 = $location.path() != '/forgot' && $location.path() != '/register' &&   $location.path() != '/postal' && $location.path() != '/';
  var urlCheck2 = $location.path() != '/jobrequest';
   if(urlCheck1 && urlCheck2){
     if($cookieStore.get('userToken') == undefined){
        $location.path('/login');
        //seems insufficient to only check if the userToken is defined to go through here. we should check that it's == XCSRF token?
     } else if($cookieStore.get('userToken') != undefined && ($location.path() == '/login' || $location.path() == '/')){
        $location.path('/home');
     }
  }
  if ($rootScope.cartItems.length > 0){
  showCart();
}

  }]);


}]);

推荐答案

您的代码中有两件事对我来说很奇怪,这可能是导致问题的原因(再次,因为我只能看到您的一些代码,我可能是错的.)

Two things in your code look odd to me, which could potentially be causing the problem (then again, since I'm only able to see some of your code, I could be wrong).

  1. 您的操作方式:

  1. The way you're doing this:

if ($location.path() == '/orders'){
  $state.go('orders');
} else if ($location.path() == '/admin'){
  $state.go('admin');
} else if ($location.path() == '/productList'){
  $state.go('products');
} else if ($location.path() == '/driver'){
  $state.go('driver');
} else if ($location.path() == '/driverOrder/:orderNumber'){
  $state.go('driverOrder');
}  else if ($location.path() == '/driverOrder/:orderNumber'){
  $state.go('checkout');
}

如果您要在配置块中设置状态(如UI路由器示例所示),则似乎不需要这样做-请参见

It seems like that should not be necessary if you're setting up your states in the config block like the UI-router examples show - see this link and scroll down to step (5). (Also, your last two else-if statements have the same clause in the if statement, so the '$state.go('checkout');' will never be executed.)

因为该阻止基于$ location.path()将用户发送到不同状态的位置高于您注册监听器的位置,所以您的应用甚至可能没有执行您所在位置的行尝试注册侦听器.我会尝试将侦听器注册上移至该大if/else块之上.另外,我也同意菲尔·托马斯(Phil Thomas)在评论中的建议,您应该至少收听$ stateChangeStart,直到您确定侦听器已正确注册为止,因为其他问题可能会阻止$ stateChangeSuccess.

Because that block where you're sending users to different states based on the $location.path() is above where you're registering the listener, your app may not even be executing the lines where you're trying to register the listener. I would try moving up the listener registration to above that big if/else block. Also, I agree with what Phil Thomas suggested in the comments, you should listen to $stateChangeStart at least until you're sure the listener is being registered properly, since other issues could prevent the $stateChangeSuccess.

编辑:此外,鉴于您最近的编辑,stateChangeStart侦听器看起来也不正确.您注册侦听器的方式应如下:

Edit: Also, given your recent edits, your stateChangeStart listener does not look right. The way you're registering the listener should be like this:

$rootScope.$on('$stateChangeStart', 
function(event, toState, toParams, fromState, fromParams){ 
    // logic
})

此外,在侦听器内部,请勿使用$ location,而仅使用您提供给侦听器的参数.例如,查看toState以查看用户要去的地方.这样做的原因是,在该函数内部(即过渡期间),您需要找出用户要去的地方,而$ location会告诉您用户已经在哪里.

Also, inside the listener, don't use $location, only use what you're given as arguments to the listener. For example look at toState to see where the user is trying to go. The reason for this is that inside that function, which is during a transition, you need to find out where the user is trying to go, while $location will tell you where the user already is.

这篇关于使用ui-router(AngularJS)时,$ rootScope.$ on("$ routeChangeSuccess)或$ rootScope.$ on(" $ stateChangeSuccess)不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆