Im trying to create an auth guard for my app. I have a auth service which has multpile functions and "isAuthenticated" is one of those. When I inject it into auth guard and try to run it I get below error. The httpclient works well when no gaurd is used. What I'm I missing? Also Canactivate is deprecated hence using CanActivateFn
import { inject } from '@angular/core';
import { CanActivateFn, Router, UrlTree } from '@angular/router';
import { AuthService } from 'src/app/services/auth/auth.service';
export const AuthGuard: CanActivateFn = (route, state) => {
const authService = inject(AuthService)
return authService.isAuthenticated()
};
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root',
})
export class AuthService {
readonly api_url = 'http://localhost:8000/api/';
constructor(private http: HttpClient) {}
login(email: string, password: string) {
......
}
register(email: string, password: string) {
......
}
authCheck() {
......
}
isAuthenticated(): any {
// this.authCheck().subscribe((data:any)=>{return data.message == "Authenticated"})
return true;
}
}
import { bootstrapApplication } from '@angular/platform-browser';
import { appConfig } from './app/app.config';
import { AppComponent } from './app/app.component';
bootstrapApplication(AppComponent, appConfig)
.catch((err) => console.error(err));
import { ApplicationConfig } from '@angular/core';
import { provideRouter,withHashLocation } from '@angular/router';
import { provideAnimations } from '@angular/platform-browser/animations';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [ provideAnimations(),provideRouter(routes, withHashLocation())]
};
import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterOutlet } from '@angular/router';
import { PrimeNGConfig } from 'primeng/api';
import { ButtonModule } from 'primeng/button';
import { HeaderComponent } from './core/header/header.component';
import { LoginComponent } from './pages/login/login.component';
import { HttpClientModule } from '@angular/common/http';
@Component({
selector: 'app-root',
standalone: true,
imports: [
CommonModule,
RouterOutlet,
ButtonModule,
HeaderComponent,
LoginComponent,
HttpClientModule
],
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
title = 'e-commerce';
constructor(private primengConfig: PrimeNGConfig) {}
ngOnInit() {
this.primengConfig.ripple = true;
}
}
Any help would be appreciated
I have tried injecting the httpclient in auth service still no luck.
You need to add provideHttpClient()
in the providers
list of bootstrapApplication
.