Home > OS >  How can I access an angular service inside a Guard?
How can I access an angular service inside a Guard?

Time:10-13

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?

CodePudding user response:

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.

  • Related