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

I am working on a login page, with a successful redirect to the home page. By default, I display the login page for this code:

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

Then, after checking the user / password data 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..') }; }; 

Forwarding does not work if I delete the second $location.url before the else section of the if . However, it does not use this url ( /blah ), it goes to home . but if url blah removed, the redirect logic does not work.

I cannot understand why I need to use two $location.url() . I would think, can someone help me understand how this redirect system works?

This may not be the best practice, I am open to suggestions on how to improve this, here is a Plunker Example

+6
source share
1 answer

All in all, this is going the wrong way IMO ...

Obviously, you need to block either side of the resource server, since the client side can always be β€œmodified” in a simple debugger ... But I think 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 knobs for this, but lets you just evaluate some approaches ...

One could: http://plnkr.co/edit/ZUKB1v?p=preview Although this requires user permission on all routes ... So ..: ((... Another option: http://plnkr.co/edit / iM9cA1? p = preview , which might be a little better ...

Finally, what people often do is provide http interceptors that are redirected to the login page when the "Unauthorized" error code is returned from the server. But it may seem more advanced than your ready.

+4
source

Source: https://habr.com/ru/post/957573/


All Articles