How to know what the current $Location is

Asked

Viewed 1,230 times

0

How do I validate when there is a change on the screen and the user clicks another hyperlink to exit the screen, the same can not allow.

Is there any ready angular function that performs this check?

At the moment I’m trying to use the option of $Location but do not know how I get the current screen of my system.

If possible I ask for your help, I thank you in advance.

  • Screenshot?... do you mean page (url)? Or controller? Or maybe route?

  • Ibotinelly, I need the url, I checked here on the internet, but I have not yet tested if I will succeed or at the end, I will have to test, but I found the following option to test and try to indicate in which controller it should fetch the function depending on the url: - $Location.url() - this function returns me in which location of the system I am, so I think it will be easier to treat the check, I will test here and let you know if it worked

1 answer

1


If you use a route system such as the ui-router, You can do this check in many ways. But before proceeding, I must inform you that what you will be doing, if you choose this alternative, is to check the status (.state) that the user is trying to access and not the URL proper - although it is also possible.

Ways you can check:

  • When accessing the page;
  • When changing state;

By declaring a .state, you must define a name, example:

.state('inicio', {
    //configurações aqui
})

This way you can check which state it is in, which state it is going to, whether there are parameters, etc.. To make this interception, you must use the following function:

$rootScope.$on('$stateChangeStart', function(event, toState, toParam, fromState, fromParam) {
    //Intercepta a mudança antes que ela ocorra
});

$rootScope.$on('$stateChangeSuccess', function(event, toState, toParam, fromState, fromParam) {
    //Intercepta uma mudança com successo
});

$rootScope.$on('$stateChangeError', function(event, toState, toParam, fromState, fromParam) {
    //Intercepta uma mudança com erro
});

Preferably, this code is best used within the .run() thus prevents any other process from being initiated prior to the checks.


Practical example

Say you own 2 .state():

  • One with free access -> .state('inicio')
  • One with restricted access -> .state('usuario')

Inside the run, you do the checks:

  • It’s going to state('user')?
  • If so, he has permission?
  • If not, redirect to start;

What the code would look like:

$rootScope.$on('$stateChangeStart', function(event, toState, toParam, fromState, fromParam) {
    /*
        Precisa ser no $stateChangeStart para evitar que o state seja carregado
        antes de verificar se ele possui permissão
    */
    if(toState == 'usuario') { //Identifica se ele está acessando o `usuario`
        /*
            Sua função de autenticação vai aqui
            Exemplo:
            val = 1; -> usuario autenticado;
            val = 2; -> usuario não autenticado;
        */
        if(val == 2) {
            //Usuario não está autenticado
            event.preventDefault(); //Evita que o state continue o serviço
            return $state.go('inicio'); //Redireciona para o inicio
        }
    }
});

This way you can make the validations and prevent it from accessing the page.


Edited as requested in comments.

Your goal is actually to authenticate the user to allow or not to access the page. Still using the ui-router you can make a statement of data within the .state() and, whenever status changes, check if the date requires login and then authenticate. But don’t do this inside the controller. If the user has arrived at the controller, that means that it has probably already loaded the other files, it is not always a good practice.

Example of state with date:

.state('inicio', {
    url: 'Inicio',
    data: {
        requireLogin: false
    }
})
.state('usuario', {
    url: 'MeusDados',
    data: {
        requireLogin: true
    }
})

And now into the run() :

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

    if(toState.data.requireLogin) {
        function validarAutenticacao() {
            //...
        };
        /*
           Sua validação de autenticação
           Ela pode ser a mesma para todos os .state()
           que possuirem requireLogin: true;
           Não precisa mais usar dentro do controller
        */
        if (validaAutenticacao == false) { //Se a autenticação for falsa
            event.preventDefault(); //Impede que a página inicie o carregamento
            //Redirecione o usuario ou faça outra manipulação aqui - como exibir um alerta ou redirecionar para a página anterior.
        }
    }
});
  • Celsom, thank you for helping, but your code only checks which page should be directed to if you have permission or not and in my case I need to block the redirect, that is, there can be no redirect action, it should stay on the same page if the system has any data changed and the only way I could validate this option is with $Location,url() and check which url it is in and use the controller of that page checking if there is any change in the registration or not, I believe I was not very clear, but I was able to understand what you suggested

  • What you want to do is another type of service. You are doing an authentication and not a route control. Another important point, if you are authenticating within a controller, your application will not be safe, as the user has already reached the final destination. In addition, you will need to authenticate to all controllers. I will edit my answer to this question.

  • @Talesborn edited.

  • actually it didn’t get to the controller, because what happens is the following: 1-I’m on the canvas where I filled in some fields, I clicked on the hyperlink REQUESTS on the left sidenav, but before doing $Location.Pach will do a check on the current screen in the controller that was already in use to see if the fields are empty or if there has already been any change in the fields, if there has already been this change, a modal will appear on the screen stating the message: - you have made changes to the Cad user screen, if you exit that screen you will now lose the changes, please continue?

  • If you click yes you do $Location.patch(), if you click no it stays on the page, you understand?

  • So this has nothing to do with permission.. but rather with the fact that the user has changed some information without saving the changes yet?

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.