I try to write an AuthGuard in Angular but i get the following Error:
Type 'typeof AuthServiceService' is not assignable to type '(request?: HttpRequest) => string | Promise'. Type 'typeof AuthServiceService' provides no match for the signature '(request?: HttpRequest): string
This is my auth-service.service.ts:
@Injectable({
providedIn: 'root'
})
export class AuthServiceService {
constructor(
private http:HttpClient,
public jwtHelper: JwtHelperService) { }
login(data):Observable<any>{
return this.http.post(baseUrl + 'ApplicationUser/login' ,data)
}
handleError(error: HttpErrorResponse) {
return throwError(error);
}
public isAuthenticated(): boolean {
const token = localStorage.getItem('token');
return !this.jwtHelper.isTokenExpired(token);
}
}
Here is my AuthGuard Service:
import { AuthServiceService } from 'src/services/auth/auth/auth-service.service';
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class AuthGuardService implements CanActivate {
constructor(public auth: AuthServiceService, public router: Router) { }
canActivate(): boolean {
if (!this.auth.isAuthenticated()) {
this.router.navigate(['']);
return false;
}
return true;
}
}
I get this error on this line on tokenGetter:
const JWT_Module_Options: JwtModuleOptions = {
config: {
tokenGetter: AuthServiceService
}
};
Can somebody help me what the response from AuthService should look like?
After some research i have found the solution. The tokenGetter Option needs a string with my token - so i returned the token from the local storage like below:
const JWT_Module_Options: JwtModuleOptions = {
config: {
tokenGetter: () => {
return localStorage.getItem('token')
}
}
};
Now my AuthGuard works as expected :) Thank you all for help! :)