简体   繁体   English

angularjs $ state和$ rootScope。$ on($ stateChangeStart)问题

[英]angularjs $state and $rootScope.$on($stateChangeStart) issue

I've went through multiple questions but haven't find a solution. 我经历了多个问题,但没有找到解决方案。

I have an issue with states handling. 我对状态处理有疑问。

$urlRouterProvider.otherwise( function($injector, $location) {
    var $state = $injector.get("$state");
    $state.go("cover");
});

$stateProvider
    .state('auth', {
        url: '/auth',
        templateUrl: '../views/authView.html',
        controller: 'AuthController as auth'
    })
    .state('users', {
        url: '/users',
        templateUrl: '../views/userView.html',
        controller: 'UserController as user'
    })
....

this how routing works in my app. 这就是路由在我的应用中的工作方式。

app.run(function($rootScope, $state, $location) {
    $rootScope.$on('$stateChangeStart', function(event, toState, fromState) {

        //ERROR IS IN THIS BLOCK
        if($rootScope.authenticated && $rootScope.onboard == 0) {

            //event.preventDefault();

            $state.transitionTo("onboard", null, {notify:false});
            $state.go('onboard');
        }
...

Everytime I change my route, that block fires hundred times, but I want it simply check whether user is authenticated and completed some forms or no and if no just redirect to the forms itself. 每次更改路线时,该阻止都会触发一百次,但我希望它仅检查用户是否已通过身份验证并填写了某些表格,或者是否仅重定向到表格本身。

I've tried different ways with preventDefault() ; 我已经用preventDefault()尝试了不同的方法; or without, same issue. 或没有,同样的问题。

Firstly, we should always try to check, if user is not already going (being redirected previously) to the state 'onboard' . 首先,我们应该始终尝试检查用户是否尚未转到(先前重定向)状态'onboard' If yes, stop any other handling ( simply return ). 如果是,请停止任何其他处理(只需return )。

$rootScope.$on('$stateChangeStart', function(event, toState, fromState) {

    // in case, that TO state is the one we want to redirect
    // get out of here   
    if(toState.name === "onboard"){
       return;
    }

    if($rootScope.authenticated && $rootScope.onboard == 0) {

        // this should not be commented
        //event.preventDefault();
        // because here we must stop current flow.. .
        event.preventDefault();

        $state.transitionTo("onboard", null, {notify:false});
        $state.go('onboard');
    }
 ...

Check the angularjs ui-router generates infinite loop 检查angularjs ui路由器生成无限循环

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

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