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

374
Visualizações
How can I access an angular service inside a Guard?

I have an Angular Service that checks if my client has a valid http-only JWT Cookie. Since I cannot access this cookie from the client I need to call the service method in my Guard to send a call to the server and see if my user is authenticated. The only problem is that I have no idea how I should get an instance of the service inside the Guard

The code I have written so far:

My guard (or at least what it should do):

export class AuthGuard implements CanActivate {
  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): boolean {

      let isAuthenticated : boolean = false;
      
      auth: AuthService = new AuthService()
      this.auth.getAuthStatus()
      .subscribe({
        res => {
          if(res.status == 200){
            isAuthenticated = true;
          }
        }
      });

      return isAuthenticated;
  }
}

My service:

export class AuthService{

  constructor(private http: HttpClient) { }

  getAuthStatus(): Observable<HttpResponse<any>>{
    return this.http.post(environment.server + environment.routes.authRoutes.status, "", {
      withCredentials: true,
      observe: 'response'
    })
  }
}

I know that I somehow need to get an instance of the http service but I dont think getting a new instance every time is a good idea. I would like to create an instance of the service once and then use it, or make it static so i dont need instances at all. What would be the best solution to this?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You can simply just inject it using the constructor

@Injectable()
export class AuthGuard implements CanActivate {

  constructor(
    private authService: AuthService,
  ) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
     
    // use 'this.authService.whatever()'

  }
}

If you want a single instance of any service that will be available everywhere in your app.

Otherwise known as a Singleton service.

You can simply add this to the services class:

@Injectable({
    providedIn: 'root'
})
export class MyServiceClass...

A singleton service is a service for which only one instance exists in an application.

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