简体   繁体   English

在Angular UI路由器中将$ state方法与$ stateChangeStart toState和fromState一起使用

[英]Using $state methods with $stateChangeStart toState and fromState in Angular ui-router

I'm writing a handler for $stateChangeStart : 我正在为$stateChangeStart写一个处理程序:

var stateChangeStartHandler = function(e, toState, toParams, fromState, fromParams) {
    if (toState.includes('internal') && !$cookies.MySession) {
        e.preventDefault();
        // Some login stuff.
    }
};

$rootScope.$on('$stateChangeStart', stateChangeStartHandler);

toState does not have the includes method. toState没有include方法。 Should I be doing something different, or is there a way to do what I'm trying to do? 我应该做些不同的事情,还是有办法做我想做的事情?

Also, when //some login stuff includes a $state.go(...) , I get an infinite loop. 另外,当//一些登录内容包含$state.go(...) ,我得到一个无限循环。 What might cause that? 是什么原因造成的?


Here's a more complete example demonstrating what we eventually got to work: 这是一个更完整的示例,展示了我们最终要进行的工作:

angular.module('test', ['ui.router', 'ngCookies'])
.config(['$stateProvider', '$cookiesProvider', function($stateProvider, $cookiesProvider) {

    $stateProvider
    .state('public', {
        abstract: true
    })
    .state('public.login', {
        url: '/login'
    })
    .state('tool', {
        abstract: true
    })
    .state('tool.suggestions', {
        url: '/suggestions'
    });

}])
.run(['$state', '$cookies', '$rootScope', function($state, $cookies, $rootScope) {
    $rootScope.$on('$stateChangeStart', function(e, toState, toParams, fromState, fromParams) {

        if (toState.name.indexOf('tool') > -1 && !$cookies.Session) {
            // If logged out and transitioning to a logged in page:
            e.preventDefault();
            $state.go('public.login');
        } else if (toState.name.indexOf('public') > -1 && $cookies.Session) {
            // If logged in and transitioning to a logged out page:
            e.preventDefault();
            $state.go('tool.suggestions');
        };
    });
});

I don't like using indexOf to search for a particular state in the toState . 我不喜欢使用indexOftoState搜索特定状态。 It feels naive. 感觉很幼稚。 I'm not sure why toState and fromState couldn't be an instance of the $state service, or why the $state service couldn't accept a state configuration override in its methods. 我不确定为什么toStatefromState不能是$state服务的实例,或者为什么$state服务不能在其方法中接受状态配置重写。

The infinite looping was caused by a mistake on our part. 无限循环是由我们方面的错误引起的。 I don't love this, so I'm still looking for better answers. 我不喜欢这个,所以我还在寻找更好的答案。

Suggestion 1 建议1

When you add an object to $stateProvider.state that object is then passed with the state. 将对象添加到$stateProvider.state ,该对象随状态一起传递。 So you can add additional properties which you can read later on when needed. 因此,您可以添加其他属性,以便以后在需要时阅读。

Example route configuration 路由配置示例

$stateProvider
.state('public', {
    abstract: true,
    module: 'public'
})
.state('public.login', {
    url: '/login',
    module: 'public'
})
.state('tool', {
    abstract: true,
    module: 'private'
})
.state('tool.suggestions', {
    url: '/suggestions',
    module: 'private'
});

The $stateChangeStart event gives you acces to the toState and fromState objects. $stateChangeStart事件使您可以访问toStatefromState对象。 These state objects will contain the configuration properties. 这些状态对象将包含配置属性。

Example check for the custom module property 检查自定义模块属性的示例

$rootScope.$on('$stateChangeStart', function(e, toState, toParams, fromState, fromParams) {
    if (toState.module === 'private' && !$cookies.Session) {
        // If logged out and transitioning to a logged in page:
        e.preventDefault();
        $state.go('public.login');
    } else if (toState.module === 'public' && $cookies.Session) {
        // If logged in and transitioning to a logged out page:
        e.preventDefault();
        $state.go('tool.suggestions');
    };
});

I didn't change the logic of the cookies because I think that is out of scope for your question. 我没有更改Cookie的逻辑,因为我认为这超出了您的问题。

Suggestion 2 建议2

You can create a Helper to get you this to work more modular. 您可以创建一个帮助器,以使它更加模块化。

Value publicStates publicStates

myApp.value('publicStates', function(){
    return {
      module: 'public',
      routes: [{
        name: 'login', 
        config: { 
          url: '/login'
        }
      }]
    };
});

Value privateStates privateStates

myApp.value('privateStates', function(){
    return {
      module: 'private',
      routes: [{
        name: 'suggestions', 
        config: { 
          url: '/suggestions'
        }
      }]
    };
});

The Helper 帮手

myApp.provider('stateshelperConfig', function () {
  this.config = {
    // These are the properties we need to set
    // $stateProvider: undefined
    process: function (stateConfigs){
      var module = stateConfigs.module;
      $stateProvider = this.$stateProvider;
      $stateProvider.state(module, {
        abstract: true,
        module: module
      });
      angular.forEach(stateConfigs, function (route){
        route.config.module = module;
        $stateProvider.state(module + route.name, route.config);
      });
    }
  };

  this.$get = function () {
    return {
      config: this.config
    };
  };
});

Now you can use the helper to add the state configuration to your state configuration. 现在,您可以使用助手将状态配置添加到您的状态配置中。

myApp.config(['$stateProvider', '$urlRouterProvider', 
    'stateshelperConfigProvider', 'publicStates', 'privateStates',
  function ($stateProvider, $urlRouterProvider, helper, publicStates, privateStates) {
    helper.config.$stateProvider = $stateProvider;
    helper.process(publicStates);
    helper.process(privateStates);
}]);

This way you can abstract the repeated code, and come up with a more modular solution. 这样,您可以抽象出重复的代码,并提出一个更具模块化的解决方案。

Note: the code above isn't tested 注意:以上代码未经测试

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM