Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

186
Visualizações
How to add token authentication in the headers with interceptor and the token can be null?

I have Application Angular13 with authentication OAuth and I try to add this token for all services.

But I don't manage undefined token. I have tried several techniques for calling the token but I always end up with an error, I want to be able to use non-authenticate services anyway

@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);
      })
    );
  }
}

i add this on ngModel

providers: [{
    provide: HTTP_INTERCEPTORS,
    useClass: TokenInterceptorService,
    multi: true,
  },],

try this

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

I currently have blank pages or incomplete loading

almost 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Try this:

const token  = this.authService.decodedAccessToken?.token || null;
almost 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda