Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

261
Visualizações
Checking for authentication status and redirecting user

In my app component, I want to check if the user is authenticated as soon as it loads and if not redirect the user to a public page immediately instead of loading the home (profile) page. I'm using the Auth0 service that can be found here: link to GitHub file

The question is, should I run this in the constructor or in ngOnInit and why?

if (auth.isAuthenticated()) {
  router.navigateByUrl(...))
}
over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

You may want to consider adding it to a route guard instead of adding it into a component constructor/ngOnInit.

I have an example here: https://github.com/DeborahK/Angular-Routing

See the auth.service.ts and auth-guard.service.ts files in the user folder. This example doesn't use Auth0, but it does have the Angular "plumbing".

over 4 years ago · Santiago Trujillo Relatório

0

In general, you should avoid putting any business logic in the constructor of components or directives.

Why?

Because, at the time when the constructor for a component is run, Angular has not yet initialized any inputs that component (or directive) may have. So, if the initialization logic depends on the value of its inputs, those inputs will not have their correct values, resulting in incorrect business logic.

But my component/directive initialization doesn't depend on its inputs!!

That may be true now, but if/when that changes, you now have to remember to move all your logic from the constructor to ngOnInit, which is just asking for trouble. And then, you'd have this inconsistency where some components use the constructor for initialization logic and others use ngOnInit, and that unnecessary inconsistency is also just asking for trouble as your application develops. It's the same reason why the strong recommendation is to always add the @Injectable decorator on all services even if you technically only need it if your service uses dependency injection - add it always so you don't forget to do it later when you actually do need it.

TLDR;

For consistency and to save yourself debugging problems later, only use your constructor in your components to capture injectables as properties - put all your other logic in ngOnInit.

NOTE

As @DeborahK pointed out, however, in this specific situation where you want to essentially prevent a component from being routed to if a certain condition is not met, a better solution may be a router guard. This feature of the router prevents the component from being initialized at all if some condition is not met.

over 4 years ago · Santiago Trujillo Relatório

0

You can create factory for check login with call API

.factory('check_login_session', function ($rootScope,ApiService,ApiEndpoint ,$location,$cookies,$timeout) {
        return {
            success :  function(response) {

                var check_login ={
                    wut_token : $cookies.user_details
                };
              return ApiService.postModel(ApiEndpoint.Models.check_login,check_login).then(function (response) {
                    if (response.SUCCESS == "FALSE") {
                         $location.path("staticpage");
                     } else {

                        return response.SUCCESS;
                    }
                })

            }
        }
    });

In the controller

check_login_session.success().then(function(res) {
            if(res == "TRUE"){
               //do as you want
            }
        });
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda