【问题标题】:How to create a global state change handler with ui-router如何使用 ui-router 创建全局状态更改处理程序
【发布时间】:2015-10-07 20:18:29
【问题描述】:

我正在构建我的第一个 Angular 应用程序,许多主要功能都被分离到它们自己的模块中。每个模块在配置中使用 $stateProvider 注册其路由。

我希望能够在一个地方为我的整个应用程序处理 $stateChangeStart/$stateChangeError,以便我可以评估授权并处理错误。我该怎么做?

目前我在我的主模块/应用程序的 $rootScope 上注册了这个处理程序,但是如果我从另一个模块导航到一个路由,然后导航到另一个路由,它不会触发。为什么?事实上,甚至 $urlRouterProvider.otherwise("xyz");不再有效。

我不喜欢复制粘贴代码,因此任何避免将此逻辑放入每个模块的解决方案都会受到赞赏。

【问题讨论】:

    标签: angularjs angular-ui-router


    【解决方案1】:

    你可以试试这样的:

    var app = {};
    
    // Route Config for a "some" module.
    function someModuleConfig($stateProvider) {
      $stateProvider.
          state('something', {
            url: '/something',
            templateUrl: 'path/to/something/something.html',
          });
    }
    
    // Module definition for "some" module.
    app.somemodule.module = angular.module('app.somemodule', []).
        config(someModuleConfig);
    
    // Route Config for the main module.
    function appConfig($stateProvider, $urlRouterProvider) {
      // Set the default redirect for any missing route.
      $urlRouterProvider.otherwise('xyz');
    
      $stateProvider.
          state('home', {
            url: '/',
            templateUrl: 'path/to/home/home.html'
          });
    };
    
    // Module definition for the main module.
    app.module = angular.module('myapp', [
      'ui.router',
      app.somemodule.name
    ]).config(appConfig);
    

    关键是你可以在主模块中注册你的路由,子路由可以在其他模块中注册。您也可以在主应用模块中注册所有路由,具体取决于您的代码结构。

    【讨论】:

    • 感谢 Johnny,这基本上就是我所拥有的,只是我在主模块的 run 方法中另外注册了我的状态更改处理程序。尽管没有任何一个处理程序被触发,但我仍然收到此错误:错误:无法从状态“newuser.accountsetup”解析“欢迎”(错误消息中的两个状态都来自另一个模块。)
    • 如果您在 run 块中注册状态更改处理逻辑,那么这个 SO link 可能会有所帮助,它引用的链接 (here) 可能会更多有用。看起来第二个链接描述了您可能希望如何处理状态更改。
    • 弄清楚了:您在 $urlRouteProvider.otherwise('xyz') 中提供的默认路由仅适用于模块。但是,您可以在主模块中的 $rootScope 上侦听“$stateNotFound”并从那里重定向以创建全局默认状态。这就是我所缺少的。
    猜你喜欢
    • 1970-01-01
    • 2014-04-24
    • 1970-01-01
    • 2019-08-28
    • 1970-01-01
    • 2016-10-27
    • 1970-01-01
    • 2013-12-11
    • 1970-01-01
    相关资源
    最近更新 更多