Error: Angular does not recognize session storage reference

While my project is up and running, I have encountered an error in the terminal.

 let obj = {
      doc_id: sessionStorage.getItem('doc_id'),
      batch_no: sessionStorage.getItem('batch_no')
    }

I attempted to make adjustments by adding the following code. However, the error persists in the terminal, even though my project functions properly in Angular 17.

let obj = {
      doc_id: sessionStorage?.getItem('doc_id'),
      batch_no: sessionStorage?.getItem('batch_no')
    }

Answer №1

Could you attempt it in this way?

 function fetchDocument(@Inject(DOCUMENT) private doc: Document) {
    const localStorage = doc.defaultView?.localStorage;

    if(localStorage) {
        let data = {
            document_id: localStorage.getItem('document_id'),
            batch_number: localStorage.getItem('batch_number')
          }
    }
}

Answer №2

Make sure to confirm that the code is executing in a web browser before attempting to access sessionStorage!

In case you are utilizing SSR, check for the presence of window, document, localStorage, and sessionStorage for verification!

private readonly platformId = inject(PLATFORM_ID);
...

...
if(isPlatformBrowser(this.platformId)){ 
    console.log('browser'); 
    let data = {
        doc_id: sessionStorage?.getItem('doc_id'),
        batch_no: sessionStorage?.getItem('batch_no')
    }
}

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

Create logic statements based on the information obtained from parsing an XML document

Looking for some assistance with writing this code. Any help is appreciated! Let's say I am extracting data from an XML file like the following: function parseXml(xml) { $(xml).find("ITEM").each(function() { var foo = $("bar", this).text ...

Enabling clients to access all static files from a Node.js + Express server

My index.js file serves as a node.js server : var express = require('express'); var app = express(); const PORT = process.env.PORT || 5000; var serv = require('http').Server(app); app.get('/', function(req, res) { res.sen ...

Retrieve identification details from a button within an ion-item located in an ion-list

<ion-list> <ion-item-group *ngFor="let group of groupedContacts"> <ion-item-divider color="light">{{group.letter}}</ion-item-divider> <ion-item *ngFor="let contact of group.contacts" class="contactlist" style="cl ...

Troubleshooting Vercel and Express DELETE request cross-origin resource sharing problem

Currently, I am in the process of developing an API using Vercel and ExpressJS. The GET and POST endpoints are functioning properly, however, I encountered an issue with the DELETE endpoint. When attempting to access the endpoint from my client-side JavaSc ...

Distinguishing a button based on its class

I am currently designing a website to showcase personalized store products. Each product info box includes a button, as shown in the screenshot below: https://i.sstatic.net/hiXiY.png Upon clicking on the "Options" button, users can view information about ...

Can D3 transform regions into drinking establishments?

I can create a graph using D3 areas, as shown in this example: https://i.sstatic.net/jaxJb.png Now, I want to add an animation to this graph. When the webpage loads, the initial figure will be displayed. Then, each area will morph into a bar chart. Addit ...

Challenge with neglected open connections from a comet

Utilizing various comet techniques like long polling and forever frame, along with iframes for cross subdomain activities, has presented a challenge during implementation. When a user refreshes the page or navigates to another page, a new request is made w ...

Having trouble generating an Xpath that can partially match a CSS selector like `a[href*="https://stackexchange.com/"]`

Looking to extract the Href of Hot Network Questions from Is there an Xpath equivalent to a[href*="https://stackexchange.com/questions?tab=hot"] //a[Href*"https://stackexchange.com/questions?tab=hot"] The code above works well, but... //a[@href='h ...

Tips for resetting and enabling file uploads with ng2-file-upload

My file upload functionality is working smoothly using ng2-file-upload. However, I am facing a challenge in handling server-side errors and resetting the file uploader. How can I achieve this? Below are the snippets of code that I am currently using: HTML ...

The issue with Lodash isEqual arises from the constructor specified by Angular

Currently, I am utilizing Lodash _.isEqual for performing a deep comparison between a local JavaScript object and another JavaScript object fetched through angular $get. The initial code indicates that the objects are not the same: $get({...}, function ( ...

Exploring the capabilities of Jasmine 2.0 by testing an AngularJS factory method that returns a promise

When attempting to test a function that returns a promise, I encounter the following error: "Error: Timeout - Async callback was not invoked within the timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL. " The specification I am using is as follo ...

How do I insert items into an ES6 Map using a specific object key/value type in Typescript?

I'm looking to utilize Maps instead of object maps to define keys and values. However, it appears that Typescript doesn't fully support index types for ES6 Maps. Are there any alternatives or workarounds available? Furthermore, I want to enforce ...

Expanding size on hover without affecting the alignment of surrounding elements

Imagine there are 10 divs on the page styled as squares, collectively known as the home page. Among these 10: 3 divs belong to the .event1 class, 5 divs belong to the .event2 class, and 2 divs belong to the .event3 class. <div class="boxes event1"> ...

Is there a way to implement a function in Javascript or CSS where hovering over a button will cause a div to scroll either left or right

I am working on creating a unique photo gallery layout with a description block positioned below the images. My goal is to incorporate two arrow buttons, one on each side of the photos, that will trigger a scrolling effect when hovered over - shifting the ...

Transitioning from Webpack to Vite: Resolving Path Alias and Ensuring Proper Imports

Recently, I decided to transition my project from Webpack to Vite with "vite": "^4.3.9",. However, upon running npm start, I encountered the following error: Error: The dependencies imported could not be resolved: In my React Typesc ...

graphic map and paintbrush

I've implemented an image map using shape circles, but now I'm looking for a way to draw visible circles or icons on the map. Is there a solution for this issue? Currently, I have used a canvas overlay on the image to draw on it This method wo ...

Exploring the properties of individual Vue components on a single page with v-for loop

Struggling to render a Vue component in a Rails app by iterating through an array of data fetched via Ajax. The Slim template (index.html.slim) for the index page includes a custom_form_item component, where items represent custom forms data from Rails and ...

Vue JS - Unable to locate module (datepicker)

Today marks my first time delving into the world of vue.js, and as expected, I've encountered an error that has me stumped. I recently incorporated the v-md-date-range-picker module into my project: (. The setup instructions provided me with the f ...

The Angular-ui typeahead feature is delivering accurate results when the backspace key is pressed

I've been using Angular-UI typeahead and it's been working fine, but I've noticed a strange behavior when I hit the backspace key - it gives the correct results. For example, if I type sector 4 The result is Sector 1 Sector 2 ...

Error occurred in the middle of processing, preventing the headers from being set

I created a custom authentication middleware, but encountered an error. I'm puzzled about what's going wrong because I expected the next() function to resolve the issue? app.use(function(req, res, next){ if(req.user){ res.local ...