Best practices for accessing session values in Angular 8's Oninit lifecycle hook

When I log in, I store the access token on session storage and try to access it in other components using the oninit() method. However, I keep getting a null value. Upon checking the console, I can see that the token is being stored in the session.

Here is how I set the session storage during a post HttpClient request:

.subscribe(
    (data: any) => { // json data

      console.log('Success: ', data);
      sessionStorage.setItem("Token ",data.access_token)
        this._router.navigate( ['dashboard'] );

  }, 

And here is how I am trying to access the token in another component:

ngOnInit() {
    let url:string = '.......';
     const token  = sessionStorage.getItem("Token");
     console.log(token);


    this.http.get(url,
    {
      headers : new HttpHeaders({
       'Content-Type': 'application/x-www-form-urlencoded',
      'Authorization' :'Bearer '+ token
      })
    }
    ).subscribe(
      (data: any)=> { // json data

       console.log('Success: ', data.data);
      this.leads = data.data;


   },
   error => {
       console.log('Error: ', error);
   }
    )
  }

} 

Answer №1

When registering the Token, ensure there are no extra spaces.

sessionStorage.setItem("Token", data.access_token)

If there is an extra space after "Token", please remove it for proper functionality.

Answer №2

Validate by utilizing sessionStorage.setItem( Token, JSON.stringify(data.access_token) );

You can also retrieve with JSON.parse( sessionStorage.getItem( Token ));

Answer №3

  localStorage.setItem("AuthToken ", data.token)// There is a typo here with an extra space after 'AuthToken'

  localStorage.setItem("AuthToken", data.token); // Corrected the typo

If it's still not functioning properly, make sure to verify if the AuthToken key is set before the initialization code in your component,

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

Utilizing the array.map method to access the key of an object within an array of arrays in TypeScript

Can I utilize array.map in TypeScript to apply a function with the parameter being the key of an object within an array? I have an array containing objects which have keys 'min' and 'max'. I am looking to use something like someArrayFun ...

Visual Studio - TypeScript project synchronization issue

Currently using the 2015 version of Visual Studio Community, I am facing an issue while working on a typescript project. Whenever I make modifications to the code, debug it, and save it using ctrl + s followed by refreshing the browser with ctrl + r, the c ...

Cannot utilize remote.require() in TypeScript due to compatibility issues

Recently, I've been facing a frustrating issue while developing an Electron application in TypeScript. I've been trying to execute a module from a renderer process using the code snippet below: import { remote } from 'electron' const ...

Error: The value of this.root_ is currently null

Attempting to utilize the material from https://github.com/material-components/material-components-web/tree/master/packages/mdc-drawer to make it work and facing challenges The code I am using: <aside class="mdc-drawer mdc-drawer--dismissible"> ...

What practical applications exist for preserving JSX post-transpilation of a tsx file?

While troubleshooting another issue, I decided to delve into Typescript's documentation on JSX usage. I discovered that some options involve converting JSX while others do not. I am puzzled as to why one would need to preserve JSX in transpiled file ...

Data loss occurs when the function malfunctions

Currently, I am working with Angular version 11. In my project, I am utilizing a function from a service to fetch data from an API and display it in a table that I created using the ng generate @angular/material:table command. Client Model export interfac ...

Tips for successfully passing the dynamic state and setState to a function in typescript

I'm encountering an issue with passing dynamic state and setState into a function using Typescript. Despite trying to use Generics, I am facing complaints from Typescript. Here is the code snippet: const handleSelectTag = (tag: { color: string; labe ...

What is the best way to modify a data parameter in Angular 2?

I am facing an issue while trying to change a data parameter in my component file: this.commandList.ListesCommandesATransmettre.forEach(data => { this.catalogs.forEach(catalog => { if (catalog.Libelle === data.Catalogue) { if ...

Can you define the type of binding value in AngularJS 1.5(6) using TypeScript?

I am looking to define the type of binding items so that I am able to utilize components similar to functions. For instance, consider a component: angular.module('app').component('navBar', new NavBar()); class NavBar{ public bin ...

Is it better to store data individually in localStorage or combine it into one big string?

When it comes to keeping track of multiple tallies in localStorage, one question arises: Is it more efficient to store and retrieve several small data points individually or as one larger chunk? For example: localStorage.setItem('id1', tally1); ...

I am curious about the types of props for the methods within the 'components' object in react-markdown

Having some trouble using 'react-markdown' in NextJs 13 with typescript. TypeScript is showing errors related to the props of the 'code' method, and after searching online, I found a solution that involves importing 'CodeProps&apos ...

Create a tuple type that encompasses all possible paths within a recursive object configuration

Consider the following templates for 'business' types, representing compound and atomic states: interface CompoundState<TName extends string, TChildren extends { [key: string]: AnyCompoundState | AnyAtomicState }> { type: 'parent&ap ...

Utilizing a mutual RxJS subject for seamless two-way data binding in Angular 2

I have a unique service dedicated to managing app configurations class Configuration { get setting() { return dataStore.fetchSetting(); } set setting(value) { dataStore.saveSetting(value); } } This configuration is linked to components t ...

Creating a Typescript project that compiles to UMD format, however, encountering the challenge of

I am trying to convert my index.ts file into a UMD index.js so that I can use it with a <script> tag. Here is the TypeScript configuration I am using: { "compilerOptions": { "outDir": "dist", "declaration& ...

The utilization of React.Component inheritance in TypeScript

In my attempt to develop a base class using React.Component and derive two classes from the base class, I have encountered an issue. Here is how I structured the classes: interface BaseItemProps { base_prop: string; } class BaseItem<P, T> exten ...

Combining various DTOs in a seamless manner for validation in TypeScript is made easy with the class-validator fusion technique

As I delved into my NestJS project, I found the class-validation aspect to be quite bothersome. It felt like I was constantly repeating the same classes with identical decorators. For example: export class DTO1 { @IsDefined() @IsString() name: ...

Issue: The function react.useState is either not defined or its output is not iterable

I'm facing an issue while programming in Next.js 13. Any help or suggestions would be greatly appreciated! Here are the relevant files: typingtext.tsx import React from "react"; export function useTypedText(text: string, speed: number, dela ...

Receiving distinct data from server with Ionic 2 promises

Utilizing ionic 2 RC0 with promises to retrieve data from the server, I am facing an issue where I consistently receive the same data in every request due to the nature of promises. Hence, my question is: How can I tackle this problem and ensure differen ...

Utilize React.useImperativeHandle() for declaring custom types

function App(){ const refEl:React.MutableRefObject<any> = React.useRef(null); // I am uncertain about the appropriate type here. React.useEffect(()=>{ if(refEl.current){ refEl.current.start() } }, []); return <Countdown ref={refEl} ...

Defining and initializing variables in TypeScript

Trying to get the hang of Angular and TypeScript, but I'm stuck on why I can't access my variable after declaring it. It looks something like this. export class aComponent implements OnInit { num : Number; num = currentUser.Id Encounterin ...