The function LocalStorage.retrieveToken() returns a null value

In my coding project, I am encountering an issue where the header authorization (Bearer + token) is not being set properly. Although there is a variable called token stored in my localstorage, when I print it, the bearer part appears to be null.

Here is the code snippet from auth.services.ts:

getToken() {
    const token = localStorage.getItem('token');
    console.log(token);
    return token;
  }

And here is the code snippet from token-interceptor.ts:

constructor(private authService: AuthService) { }

intercept(req, next) {

  const tokenizeReq = req.clone({
    setHeaders: {
      authorization: `Bearer ${this.authService.getToken()}`
    }
  });
  return next.handle(tokenizeReq);
}

When checking the console outputs,

https://i.sstatic.net/lAJKX.png

I have also examined the Network variables and LocalStorage contents,

The issue appears to be with setting 'null'. Any insights on why this is happening would be greatly appreciated.

Answer №1

Would you mind giving this a shot:

setTimeout(function() {
    let token = localStorage.getItem('token');
}, 50);

If you're attempting to retrieve the token value immediately after setting it, it won't work and you'll receive null. Make sure to call localStorage.getItem only after the setItem function has completed.

Answer №2

In my opinion, it may take some time to establish the token as a local variable. To do this, please utilize the await and async functions to create and set the token.

For example:

async setToken(token){
  await localStorage.setItem('token', token);
}

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

Top method in Angular 6 for verifying if a scrollable section has been scrolled to the very bottom

I am searching for a reliable solution in Angular 6 to determine whether a scrollable host component has reached its maximum scroll bottom. Despite my efforts, I have been unsuccessful in finding a functioning example of a function that can detect if a cu ...

"Mastering the art of text animation: A beginner's guide

If you want to see a cool moving text animation, simply head over to this link: . The text will automatically type out and then clear just like the example below: https://i.sstatic.net/dAZW6.png Ever wondered how to create this kind of text animation? A ...

Array of Typed Objects in TypeScript

Here is the setter I created in TypeScript: public set data(data: Array<Data>) { console.log(data[0].getterProperty); console.log(data[0] instanceof Data); console.log(typeof data[0]); this.setGridDataIfReady(); } If data contains only one ...

Unable to find the symbol 'Whitelist' in an Ionic Capacitor application

I encountered this error and I'm not sure what is causing it. I am having trouble building on android. My current setup includes: Angular CLI: 8.1.3 Node: 16.17.1 Capacitor: 6.20.3 ...

No issues raised by Typescript/tslint regarding this in arrow function

After making some creative adjustments, this is what I came up with: const TopBar = () => ( <Button onPress={this.onPress} // No errors shown /> ) Although all my other rules in tslint.json are functioning properly. Is there a way to ma ...

Can Envs in Bit be linked together?

My React environment is set up at this link: . It is configured with the following dependencies: { /** * standardize your component dependencies. * @see https://bit.dev/docs/react-env/dependencies **/ "policy": { // peer and dev ...

The ngOnInit lifecycle hook is not triggered on the error page component

Creating an error page for an Angular 4 application. In an attempt to display information about unhandled exceptions, I have implemented the GlobalErrorHandler to catch errors and redirect users to an ErrorComponent page. However, when the error occurs, t ...

What prevents me from utilizing the Router object within a function set for the then() of a CRUD delete operation in my Angular service?

I'm currently tackling a challenge in my Angular project where I am attempting to utilize a Router class to navigate to a specific page from within a service class. Allow me to elaborate on my predicament. The service class in question looks like thi ...

Tips for creating a typescript typeguard function for function types

export const isFunction = (obj: unknown): obj is Function => obj instanceof Function; export const isString = (obj: unknown): obj is string => Object.prototype.toString.call(obj) === "[object String]"; I need to create an isFunction method ...

Navigating Timezones with PrimeNG Calendar Component <p-calendar>

I am experiencing an issue with PrimeNG in a multi-user environment where each user is in a different timezone. I need all users to submit their form data in EST, but it seems like the browser is converting the dates to the user's local timezone upon ...

Using Laravel 5.2 passport for secure authentication with Angular 2

Being new to Laravel Passport, I find it quite confusing. I've watched Taylor Otwell's tutorial on Passport but still can't figure out if it's possible to authenticate an Angular app with Laravel Passport. My goal is to develop a Full ...

The "ng2-CKEditor" package is experiencing compatibility issues with TypeScript in Angular 2

Currently, I am in the process of setting up CKEditor in my angular2 application. My backend platform is node.js and for this purpose, I am utilizing the ng2-CKEditor npm module. Below, you can find snippets from respective files. index.html:: <html& ...

Angular HTTP GET requests fail to execute commands

I'm attempting to send a request to an API, like the SWAPI API, in my Angular application. Here's how I've set it up: Within my app.module file: ... ... import { HttpClientModule } from '@angular/common/http'; declarations: [ ...

What could be causing the malfunction of getter/setter in a Vue TypeScript class component?

Recently delving into the world of vue.js, I find myself puzzled by the unexpected behavior of the code snippet below: <template> <page-layout> <h1>Hello, Invoicer here</h1> <form class="invoicer-form"> ...

Problem with timing in token interceptor and authentication guard due to injected service

Currently, I am facing an issue where I need to retrieve URLs for the auth service hosted on AWS by reading a config.json file. In order to accomplish this, I created a config service that reads the config file and added it as a provider in app.module. Eve ...

In Angular and Typescript, adjusting the index in one dropdown will automatically update the selected option in another dropdown

I'm a newcomer to Angular and I could use some assistance with the following requirement: In my Angular template, I have two dropdowns. I want the selection in one dropdown to automatically reflect in the other dropdown. Both dropdowns pull their val ...

Encountering a 404 error in Angular on localhost while trying to consume a GET API from a different localhost port - Could

After making the switch from the in-memory-web-api URL to the database URL, I started encountering a 404 error in the JavaScript console of my Angular app. Click here to see the 404 error in the JavaScript console I have my Angular app running on lite ...

When utilizing the RTK Query custom hook in Typescript, an error may occur stating "Invalid hook call. Hooks can only be called inside the body of a

While delving into next.js with rtkquery and typescript, I encountered an error in the useEffect hook within GoogleMapComponent.tsx. The React site pointed out that I was violating some rules of hooks usage, but this is a functional component being used in ...

saving the MediaObject to Ionic's storage with the set method

I attempted to save a Media Object on ionic storage, but encountered an error message stating: "error while saving media object in storage.set" https://i.sstatic.net/5jEaQ.jpg How can I successfully save a media object using storage.set and retrieve it ...

Executing cypress tests with tags in nrwl nx workspace: A simple guide

Currently, I am working within a nrwl nx workspace where I have set up a cypress BDD cucumber project. My goal is to run cypress tests based on tags using nrwl. In the past, I would typically use the "cypress-tags" command to achieve this. For example: &q ...