簡體   English   中英

app.run中$ stateChangeStart內的$ state.go無法正常工作

[英]$state.go inside $stateChangeStart in app.run not working

注意:這是一個示例代碼, window.has_redirected只是為了使問題更容易。

此代碼不會重定向到dashboard

我在網上看到它不起作用的原因是$state還沒有准備好......但是我看到網上的教程正在做一些非常類似的事情。

我該如何解決?

(function(){
"use strict";

angular.module('app.routes').config( function($stateProvider, $urlRouterProvider ) {

    $urlRouterProvider.otherwise('/');

    $stateProvider
    .state('login',{
        url: '/',
        ...
    })
    .state('dashboard', {
        url: '/dashboard',
        ...
    });


} ).run( function( $rootScope, Users, $state ) {
    $rootScope.$on( "$stateChangeStart", function(event, toState, toParams
                                                     , fromState, fromParams){

        if ( !window.has_redirected ){
            window.has_redirected = true;
            window.console.log('going to dashboard');
            $state.go('dashboard');
        }

    });
} );
})();

一個工作的plunker

你幾乎就在那里......我們真正需要的是通過以下方式停止執行流程:

event.preventDefault();

這將停止當前的狀態更改,並將進行重定向$state.go()

$rootScope.$on( "$stateChangeStart", function(event, toState, toParams
                                                 , fromState, fromParams){

  // I would always check if we are not already on the way
  // to the "redirection" target. 
  var isGoingToDashboard = toState.name === "dashboard";
  if(isGoingToDashboard)
  {
    return;
  }

  // this remains
  if ( !window.has_redirected ){
      window.has_redirected = true;
      console.log('going to dashboard');

      // HERE is the essential breaker of the execution
      event.preventDefault();
      $state.go('dashboard');
  }
});

這里檢查它

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM