当应用程序打开,首次有条件的页面显示首次、有条件、应用程序、页面

2023-09-14 00:24:17 作者:岛是海的疤

我刚开始学习的角度和放大器;&安培;棱角分明的UI路由器和我试图找出如何确定应用程序被打开的第一时间向用户发送到登录页面或主页时。

Hi I am just starting to learn angular && angular-ui-router and am trying to figure out how to determine when the app is opened for the first time to send the user to the login page or home page.

这是我迄今为止:

codeArtApp.config(function($stateProvider, $urlRouterProvider){
$stateProvider
    .state('login',{
        url : '/login',
        templateUrl:'App/scripts/login/loginView.html',
        controller: 'loginCtrl'
    })
    .state('profile', {
        url : '/profile',
        templateUrl:'App/scripts/login/loginView.html',
        controller: 'profileCtrl'
    })
    .state('404', {
        url: '/404',
        templateUrl:'App/scripts/views/404.html'
    });


$urlRouterProvider.otherwise("404");

});

codeArtApp.run(['$state', '$rootScope', function($state, $rootScope, $log){
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState){
    if(fromState.url === '^' && toState.url !== 'login'){
        $state.go('login');
    }

});

}]);

我这里假设的是,如果 fromState.url 设置为 ^ 则应用程序启动的第一次了。

What I assumed here is that if fromState.url is set to ^ then the application is starting for the first time.

有关某种原因,这code进入一个无限循环,我这个GT堆栈跟踪:

For some reason this code enters an infinite loop and I gt this stacktrace:

现在从我可以讲这个事情,因为如果事件的 $ state.go('登录')得到执行 toState.url 总是 404

Now from what I can tell this happened because event if $state.go('login') gets execute toState.url is always 404.

我希望,如果 $ state.go('密码')被执行 toState.url 本来设置登录和通话将不能再执行。

I had hoped if $state.go('login') gets executed toState.url would have been set to login and that call would not be executed anymore.

我可能不会在正确的地方可以设置这个逻辑...

I may not be setting this logic in the right place...

谁能告诉我如何显示conditionaly页角中实现?

Can anyone tell me how conditionaly page displayed is achieved in Angular?

推荐答案

有对工作的 plunker ,主要的变化都显示在code:

There is a link to working plunker, the main changes are shown in the code:

codeArtApp.run(['$state', '$rootScope',
 function($state, $rootScope, $log) {

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

      // instead of 
      // toState.url !== 'login'
      // we compare 
      // toState.name !== 'login'
      var shouldLogin = fromState.url === '^' 
              && toState.name !== 'login';

      if(shouldLogin)
      {
        // this way we stop current execution
        event.preventDefault();
        // and navigate to login
        $state.go('login');  
      }
    });
 }
]);

toState.url 将包含URL,即/登​​录而不是'登录'。同时检查: State Change事件,了解更多关于。在事件preventDefault(); 。该 plunker 表示对上述...

The toState.url would contain the url, i.e. '/login' instead of 'login'. Also check the : State Change Events to see more about the event.preventDefault(); . The plunker showing the above...

 
精彩推荐