What is the process for implementing token authentication within headers using an interceptor, especially when the token may be null?

In my Angular13 application with OAuth authentication, I am encountering issues when trying to add the token for all services.

I have been unsuccessful in managing the undefined token. Despite trying various techniques to retrieve the token, I always encounter errors. However, I still want to be able to utilize non-authenticated services.

@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 have added this on ngModel

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

Attempted fixes:

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

As a result, I am experiencing blank pages or incomplete loading on my application.

Answer №1

Give this a shot:

let authToken = this.authService.decodedAccessToken?.token || null;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

include a new value to the current state array within a react component

I am working with an array in React State and I need to add a new property called Value. However, every time I try to add it, it creates a new item in the array. What I actually want is for the new property to be added as follows: value: '' Belo ...

Transferring PHP array data into JavaScript array values

A PHP array structure is presented below. Array ( [0] => hal([[br,1],[cl,4]]) [1] => alk([[nc(1),1,2],[nc(1),3]]) ) I need to convert this array into JavaScript format like so: var hal=[["br",1],[cl,4]]; var alk=[[nc(1),1,2],[nc(1),3]]; In ...

Certain images fail to load when the properties are altered

I am facing an issue where the images in my child components do not show up when props are changed, unless the page is manually refreshed. There are no 404 errors for the images, and even when I inspect the image element, I can see the correct image link b ...

Utilize different versions of jQuery along with various plugins

I have integrated the AdminLTE Template into my project, which requires jQuery Version 3.X. Additionally, I am using the Flotchart jQuery library, which specifically needs jQuery Version 1.11.3. To handle this conflict, I have implemented the $.noConflic ...

Tips on how to showcase the current time in the local timezone on Next.js without encountering the error message "Text content does not match server-rendered HTML."

Currently, I am sharpening my Next.js skills by building a blog. My current challenge involves formatting a static ISO time string (which represents the creation time of blog posts) to match the local timezone of the user. <div className='post-time ...

Tips for designing a custom TypeScript 5 property decorator

I have a decorator in TypeScript: const bindMethod = (method: any): PropertyDecorator => ((target: any, name?: PropertyKey): any => { if(name === undefined) { throw new Error('Bound decorator must be used with a property name.& ...

What is the best way to eliminate the input range in a React date range picker?

Here is an image illustrating a date range picker: https://i.stack.imgur.com/pwKaI.png I am looking to remove the labels for days before today and starting from today in the date range picker. How can I achieve this? Below is my code snippet: class Better ...

Encountering issues when attempting to establish the initial date of a react DatePicker based on the user's timezone

I am currently working on a React project and facing an issue with setting the default date of a DatePicker component to the user's timezone received from an API. Despite several attempts, I keep encountering an error whenever I try to inject the date ...

What is the process for decoding HTML content that is wrapped within JSON data?

I have a web application built using asp.net that utilizes ajax calls. Below is the code snippet for my web method which successfully responds to the ajax call. ADController adc = new ADController(); DataTable dt = adc.GetGeneral(Convert.ToInt32(A ...

Obtain offspring from a parent element using jQuery

$(document).ready(function() { $.ajax({ type: "POST", url: 'some/url', data: { 'name':'myname' }, success: function (result) { var result = ["st ...

Emscripten WebAssembly: Issue with Exporting Class "Import #13 module="GOT.func" error: the module does not exist as an object or function"

Exploring the potential of WebAssembly in a project as an importable function module, I decided to dive into using C++ with Emscripten. Implementing functions was smooth sailing, but running into obstacles when it comes to classes. My goal is to expose and ...

XPath using JScript

I'm a beginner with Selenium and I'm curious about how the value in the text box is loaded when there's no value visible in the HTML tag: <input type="text" name="qty" id="qty" maxlength="5" value="" title="Qty" class="quantity-input qty ...

Is there a way to modify the value of an object in a Vuex store using actions in Vue.js?

I have data stored in an array within the state and I need to update a specific object. How can I change the value of the object with id 1 to true using Vuex actions? state.js const array=[] mutations.js storeArray(state, data) { state.array = data ...

The script resource is experiencing a redirect that is not permitted - Service Worker

I have integrated a Service Worker into my Angular application, and it works perfectly when running on localhost. However, when I attempt to deploy the code in a development or different environment, I encounter the following error: Service worker registra ...

What is the best way to deliver flash messages using Express 4.0?

Currently, my web application requires authentication, and I am encountering an issue with the signup page. If a user tries to sign up with an email that is already in the database, I want to display an error message. Here is the code snippet I am using on ...

What is the best way to incorporate additional properties while utilizing useSession in Next.js with TypeScript?

I've encountered an issue while trying to add new properties using useSession() in a TypeScript environment. Although it works on console.log, there is an error related to the type mismatch. The useSession() function typically returns name, email, an ...

What is the best way to convert a locale code into a language name with i18next?

In the application I'm working on, there is a language selector feature that allows users to choose the display language for the app. Currently, we only have limited options available, but there are plans to expand the list in the future. My goal is t ...

Utilizing local storage functionality within AngularJS

I've been encountering challenges while trying to integrate local storage using ngStorage in my ongoing AngularJS project. Despite fixing what seems to be the root cause of data type problems and errors during debugging, issues persist. Here is the P ...

What's the best way to modify the style property of a button when it's clicked in

I am working with a react element that I need to hide when a button is clicked. The styles for the element are set in the constructor like this: constructor(props) { super(props); this.state = { display: 'block' }; this. ...

How to iteratively process JSON array using JavaScript?

I am currently attempting to iterate through the JSON array provided below: { "id": "1", "msg": "hi", "tid": "2013-05-05 23:35", "fromWho": "<a href="/cdn-cgi/l/email-pro ...