AngularJS: Understanding $rootScope.$on('$routeChangeSuccess

你说的曾经没有我的故事 提交于 2020-01-01 10:03:19

问题


I am working on a login page, on success, it redirect to home page. By default I show login page this code:

app.run(function($rootScope, $location) {
  $rootScope.$on('$routeChangeSuccess', function() {
      $location.url("/login");
  });
});

Then after validating the user/pass details from the backend I take the user to the home page:

$scope.login = function() {
    if ($scope.username === 'admin' && $scope.password === 'pass') {
      console.log('successful')
      $rootScope.$on('$routeChangeSuccess', function() {
          $location.url("/home")
      });
      $location.url("/blah");
    } else {
      $scope.loginError = "Invalid username/password combination";
      console.log('Login failed..')
    };
  };

The redirect doesn't seem to work if I remove the second $location.url before the else section of the if statement. It is however not using that url (/blah), it goes to home. but If url blah is removed it the redirect logic does not work.

I can't seem to understand why I have to use two $location.url(). I would appretiate if someone can help me understand how this redirect system works?

This might not be the best practice, I am open to suggestions on how to improve this, here is Plunker example


回答1:


All in all this is going down a wrong path IMO...

Obviously you need to lock down any resources server side as client side can always be "changed" in a simple debugger... But I guess you already know that...

Alternative routing solutions like https://github.com/dotJEM/angular-routing or https://github.com/angular-ui/ui-router IMO gives you some better handles for this, but lets just evaluate some approaches...

One would be: http://plnkr.co/edit/ZUKB1v?p=preview Although that requires you resolve the user on all routes... So.. :(... Another would be: http://plnkr.co/edit/iM9cA1?p=preview which might be a little better...

Finally, what people often seem to do is provide http interceptors that redirects to the login page when a "Unauthorized" error code is returned from the server. But this could seem to be a more advanced approach than your ready for.



来源:https://stackoverflow.com/questions/19833588/angularjs-understanding-rootscope-onroutechangesuccess

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!