Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

178
Views
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 answers
Answer question

0

Try this:

const token  = this.authService.decodedAccessToken?.token || null;
almost 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!