使用 ui-router(AngularJS) 时,$rootScope.$on("$routeChangeSuccess) 或 $rootScope.$on("$stateChangeSuccess) 不起作用

2024-04-04

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

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

  }]);


}]);

你的代码中的两件事对我来说看起来很奇怪,这可能会导致问题(话又说回来,因为我只能看到你的一些代码,所以我可能是错的)。

  1. 你这样做的方式:

    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 路由器示例所示),则似乎没有必要这样做 - 请参阅这个链接 https://github.com/angular-ui/ui-router#nested-states--views并向下滚动至步骤 (5)。 (此外,最后两个 else-if 语句在 if 语句中具有相同的子句,因此 '$state.go('checkout');' 将永远不会被执行。)

  2. 由于您根据 $location.path() 将用户发送到不同状态的块位于您注册侦听器的位置之上,因此您的应用程序甚至可能不会执行您尝试注册侦听器的行。我会尝试将侦听器注册移至那个大的 if/else 块之上。另外,我同意 Phil Thomas 在评论中的建议,您应该至少监听 $stateChangeStart 直到您确定监听器已正确注册,因为其他问题可能会阻止 $stateChangeSuccess 。

Edit:另外,考虑到您最近的编辑,您的 stateChangeStart 侦听器看起来不正确。注册监听器的方式应该是这样的:

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

另外,在侦听器内部,不要使用 $location,仅使用为侦听器提供的参数。例如,查看 toState 以了解用户想要前往的位置。这样做的原因是,在该函数内部,即在转换期间,您需要找出用户试图前往的位置,而 $location 会告诉您用户已经在哪里。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 ui-router(AngularJS) 时,$rootScope.$on("$routeChangeSuccess) 或 $rootScope.$on("$stateChangeSuccess) 不起作用 的相关文章

随机推荐

  • 找不到 Magick-config [重复]

    这个问题在这里已经有答案了 可能的重复 ImageMagick RMagick 无法安装 RMagick 2 13 1 找不到 Magick 配置 https stackoverflow com questions 3894225 imag
  • 为什么在循环之外生成随机数会导致它始终相同?

    当我在 while 循环内创建一个随机数作为局部变量时 一切正常 但是当我生成一个随机数作为全局变量时 我就会陷入无限循环 我不明白这会如何以及为什么会产生任何影响 目标是通过 While 循环输出所有小于 0 7 的随机数 这是创建无限循
  • OnResume 相机重新初始化黑屏

    我有个问题 初始化相机进行预览并使另一个应用程序进入焦点后 然后返回我的应用程序 预览显示为黑色 如果我继续拍照 它会拍摄我通常将相机指向的位置的照片 我在 OnResume 覆盖上做错了什么吗 相关代码如下 public void Rel
  • Safari 忽略 tabindex

    我在一个文本框旁边有 2 个按钮 在这两个按钮后面有另一个文本框 第一个文本框的 tabindex 为 1000 第一个按钮为 1001 第二个按钮为 1002 第二个文本框的 tabindex 为 1003 当我按 Tab 时 tabin
  • 在 Mac 终端的 vim 语法突出显示中启用斜体

    我想让 vim 以斜体显示我的评论 并且我知道我需要放置 cterm italic in the hi Comment 我正在使用的 color vim 文件中的行 然而 这对文本显示没有影响 我怀疑这与某些 Terminal app 设置
  • 如何在java中加载和使用本机库?

    我有一个 java 类 调用本机方法并尝试加载库 import java io UnsupportedEncodingException public class Main public static native String getMy
  • C hsearch 查找之前未输入的值

    这是一个后续问题这个问题 https stackoverflow com q 34749026 2451238 Since I solved https stackoverflow com a 34749797 2451238我感觉剩下的问
  • python pandas:将带有参数的函数应用于一系列

    我想将带有参数的函数应用于 python pandas 中的一系列 x my series apply my function more arguments 1 y my series apply my function more argu
  • 如何让CSS输入范围拇指首先不出现

    我正在进行食物成瘾调查 我需要一个如下所示的输入范围 from https css tricks com styling cross browser company range inputs css https css tricks com
  • 如何在适用于 Android 的 Google Analytics v4 SDK 中通过 XML 配置试运行和日志级别选项?

    The 参数 https developers google com analytics devguides collection android v4 parametersGoogle Analytics v4 SDK 使用的 XML 配
  • 更新应用程序-Android

    我正在开发一个 Android 应用程序 我的应用程序包含一个本地数据库 位于应用程序的 assests 文件夹中 当用户安装应用程序时 它会复制数据库以便使用它 然后用户可以向其中添加项目 我的问题是 如果我将为我的应用程序发布更新 它会
  • distanceFromLocation - 计算两点之间的距离

    只是一个关于核心位置的简单问题 我正在尝试计算两点之间的距离 代码如下 void locationChange CLLocation newLocation CLLocation oldLocation Configure the new
  • Python Tesseract 无法识别这种字体

    我有这个图像 我想使用 python 将其读取为字符串 我认为这并不难 我发现了 tesseract 然后是使用 tesseract 的 python 脚本的包装器 所以我开始阅读图像 效果很好 直到我尝试阅读这张图像 我是否需要训练它来读
  • Java中小型不可变对象的缓存策略?

    我正在开发一个应用程序 它创建大量小型 不可变的 Java 对象 一个例子可能是 public class Point final int x final int y final int z 许多 Point 实例可能需要引用相同的 x y
  • 在哪里使用带循环的 return 语句?

    有时我会感到困惑where使用return陈述 我明白它的作用 只是我没有正确理解它的位置 这是相同代码的简短示例 正确方法 def product list list of numbers c 1 for e in list of num
  • 使用 URI (Xamarin) 的 Android FFImageLoading

    我正在尝试从光标加载联系人图像 因此我有每个图像的 URI 但我想使用 FFImageLoading 库将这些图像添加到视图中 以便我可以轻松加载占位符并进行圆形变换 但是 我在使用具有 URI 的库时遇到困难 我尝试使用 Path 将 U
  • android:如何从twitter获取趋势?

    我想从 Twitter 获取趋势 任何人都可以帮我解决这个问题吗 我已经使用以下方式登录了login button并且获得了活跃的会话 现在问题是如何获取趋势标签 https dev twitter com rest reference g
  • 如何在 Rmarkdown 演示文稿(滑动)中回显代码之前显示块输出?

    我最近开始在 Rmarkdown 中使用 Slidy 演示模板 并且喜欢每张幻灯片如何允许您向下滚动以获取更多内容 我使用它的一种方法是与我的学生共享绘图 请参阅下面的示例代码 在一张幻灯片上 我可以显示绘图以及用于创建绘图的确切代码 可以
  • 为什么 VSCode 在启动调试器之前不激活 conda?

    当我在 VSCode 中启动调试器时 只有在调试过程因 缺少必需的依赖项 导入错误而停止后 conda 环境才会被激活 立即重新启动调试器就可以正常工作了 此问题发生在 Anaconda base 和其他环境中 测试代码 import pa
  • 使用 ui-router(AngularJS) 时,$rootScope.$on("$routeChangeSuccess) 或 $rootScope.$on("$stateChangeSuccess) 不起作用

    我在应用程序中使用 UI router 来嵌套视图 但同时我想在路由更改时监听事件 在使用 UI router 之前 routeChangeSuccess 触发得很好 但在 ui router 之后 它不会触发 文档建议使用 viewCon