I create a functional guard in angular 17
import { Inject } from '@angular/core';
export const checkoutGuard: CanActivateFn = (route, state) => {
const customerService = Inject(CustomerService);
const router = Inject(Router);
if(customerService.isAuthenticated()) {
return true;
} else {
return router.navigateByUrl('/login');
}
};
I get the error customerService.isAuthenticated is not a function.
I declared the service in app.config.ts providers: [provideRouter(routes), provideHttpClient(), CustomerService,]
this what iI declared in routes {path:'checkout', component:CheckoutComponent, canActivate:[checkoutGuard]}
this is the service class
@Injectable({ providedIn: 'root' })
export class CustomerService {
isAuthenticated():boolean { return true; }
}
The root cause of the issue is to use
injectinstead ofInject, please change itimport:
inject-> used outside constructor to load dependencies from DIInject-> used inside constructor to load dependencies from DI (sometimes needed)We can remove
CustomerServicefrom theapp.config.tsproviders array, since that is reserved for environment providers only, then in the customers service we can setprovidedIn: root, which means the service is accessible throughout the application, so even inside guards!Then you need to check how you have defined,
isAuthenticatedit should be a function/method, if its a property please change the if condition to