Tengo la aplicación Angular13 con autenticación OAuth e intento agregar este token para todos los servicios.
Pero no administro un token indefinido. Probé varias técnicas para llamar al token, pero siempre termino con un error, quiero poder usar servicios sin autenticación de todos modos
@Injectable({
providedIn: 'root',
})
export class TokenInterceptorService implements HttpInterceptor {
constructor(private authService: AuthService) {}
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
const {token} = this.authService.decodedAccessToken;
if (token) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${token}`,
},
});
}
return next.handle(request).pipe(
catchError((err) => {
console.error(err);
const error = err.error.message || err.statusText;
return throwError(error);
})
);
}
}
agrego esto en ngModel
providers: [{
provide: HTTP_INTERCEPTORS,
useClass: TokenInterceptorService,
multi: true,
},],
prueba esto
const token = this.authService.decodedAccessToken;
// or this
typeof token != 'undefined' && token
// no condition
Authorization: `Bearer ${this.authService.decodedAccessToken}`,
// and on error 401
this.authService.logout();
//
return next.handle(request):
angular-oauth2-oidc.mjs:1398 error loading discovery document TypeError: Cannot destructure property 'token' of 'this.authService.decodedAccessToken' as it is undefined.
/// or
core.mjs:6509 ERROR Error: Uncaught (in promise): TypeError: Cannot read properties of null (reading 'message')
/// or
status: 401
Actualmente tengo páginas en blanco o carga incompleta
Prueba esto:
const token = this.authService.decodedAccessToken?.token || null;