• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

290
Views
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?

about 3 years ago · Santiago Trujillo
1 answers
Answer question

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.

about 3 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error