Utilizing Session storage throughout an Angular 2 application

I currently store a session variable as a JSON value in my home.component.ts. This variable needs to be accessed in various locations within the application.

This is my code snippet:

.do(data => sessionStorage.setItem('homes', JSON.stringify(data)))
var session = sessionStorage.getItem('homes'); 

What is the best way to access the session variable across the entire application?

Answer №1

Create a service and utilize it within your components. Include methods to set and get sessionStorage data in this service.

For instance:

import { Injectable } from '@angular/core';

@Injectable()
export class HomeService {

  constructor() { }

  public setData(data: any){
    sessionStorage.setItem('homes', JSON.stringify(data));
  }

  public getData(){
   return JSON.parse(sessionStorage.getItem('homes'));
  }
}

Next, in your home.component.ts file

constructor(private homeService: HomeService){}

ngOnInit(){
this.homeService.setData(data...); //pseudocode
}

To retrieve the data, simply call homeService.getData().

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

Verify the dimensions of the file being uploaded

I have a file uploader component that requires a dimensions validator to be added. Below is the code for the validator: export const filesDimensionValidator = (maxWidth: number, maxHeight: number): ValidatorFn => (control: AbstractControl): Vali ...

Can you provide some guidance on utilizing a for loop within Angular?

Storing the values entered by the user in an input field as "values" and having another array, "existing userdetails," returned from the backend that contains all details of existing users, I am faced with the task of comparing these two sets of data. I h ...

Unexpected Issue: Angular 12 Encounters JIT Compiler Unavailability

Lately, I've been encountering a persistent issue with an error message: Uncaught Error: JIT compiler unavailable. Ever since I upgraded from Angular version 8 to 12, whenever I run the ng build --prod --output-path = dist command and build Angular, e ...

Error: Interface declaration for _.split is missing in the Lodash.d.ts file

For my current typescript project that heavily relies on Lodash with lodash.d.ts, I've encountered an issue with the _.split function not being implemented yet. It's listed under the 'Later' section in the .ts file. I need to find a wo ...

Navigating through various Angular 7 projects in Express using JWT authentication and role-based routing

In my Angular 7 project, I have developed multiple applications for different roles such as admin, user, and editor. Each role has its own set of components and views. When a logged-in user accesses the application, they are directed to their respective r ...

Delivering an Angular2 application from a base URL using Express

I currently have an Angular2 application running alongside a simple express server. Is there a way to only display my application when a user navigates to a specific route, like '/app' for example? If so, how can this functionality be implemented ...

Data retrieval from DynamoDB DocumentClient does not occur following a put operation

I am currently working on testing a lambda function using the serverless framework in conjunction with the sls offline command. The purpose of this lambda is to connect to my local DynamoDB, which has been initialized with a docker-compose image, and inser ...

What is the best way to convert a JSON string received from Angular into a Java Object within a Spring

I am currently utilizing WebSocket to create a chat application. Below is the code from my Angular application that sends a MessageModel object to the backend after converting it into a JSON string: sendMessage(message: MessageModel){ let data = JSON.str ...

Difficulty in HttpRequest handling between Angular and .Net

My http response seems to be causing some trouble, and I'm completely stumped on what the issue might be. Can someone provide assistance, please? import { Component, OnInit } from '@angular/core'; import {SharedService} from 'src/app/sh ...

Troubleshooting Issue with Angular 5: Inability to Hide Elements for Non-Authenticated Users

Below is the code from app.component.html <nav class='navbar navbar-default'> <div class='container-fluid'> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-targ ...

Experimenting with Typescript, conducting API call tests within Redux actions, mimicking classes with Enzyme, and using Jest

I am facing an issue where I need to mock a class called Api that is utilized within my redux actions. This class is responsible for making axios get and post requests which also need to be mocked. Despite following tutorials on how to mock axios and class ...

Dealing with an unspecified parameter can be tricky - here's how you

Currently, I am in the process of developing an angular application. In this project, there is a specific scenario that needs to be handled where a parameter is undefined. Here's a snippet of my code: myImage() { console.log('test') ...

Merge arrays values with Object.assign function

I have a function that returns an object where the keys are strings and the values are arrays of strings: {"myType1": ["123"]} What I want to do is merge all the results it's returning. For example, if I have: {"myType1": ["123"]} {"myType2": ["45 ...

Obtain the query parameter before undergoing redirection within Angular version 14

In my Angular application, I am facing a challenge where I need to display a specific message to the user once they click on a link that has been sent to them via email. The link is intended to open a page within the app at the URL: "localhost:8080/?d ...

Retrieve the attributes of a class beyond the mqtt callback limitation

Currently, I am utilizing npm-mqtt to retrieve information from a different mqtt broker. My objective is to add the obtained data to the array property of a specific class/component every time a message is received. However, I'm facing an issue wher ...

Oops! There seems to be an issue: Uncaught promise error - ReferenceError: google is not defined

I've integrated Angular 2 with Google Maps Places Autocomplete in my project, but I encountered an error: ERROR Error: Uncaught (in promise): ReferenceError: google is not defined Here's the HTML snippet: <agm-map id="googleMap"> ...

I have a Visual Studio 2019 solution that consists of two projects - one is an Angular project and the other is written in TypeScript. I have successfully configured

We are currently utilizing Visual Studio 2019 (not the VS Code version) for our project. Within this solution, we have multiple projects included. One of these projects contains Angular code that we compile using the traditional 'ng build' comma ...

retrieve object from s3 using angular and open it as a pdf

I'm attempting to access a file from an s3 bucket using Angular and display it as a PDF. I have a node service set up to retrieve the object, which I then call from Angular. However, when I try to open the PDF in Angular, it appears as a blank (white) ...

I have successfully implemented useLazyQuery in a functional component, but now I am looking to integrate it into a class component. Can you provide guidance on how to achieve

Recently, I encountered an issue with my functional component that contains 3 checkboxes and 1 button. I utilized the useLazyQuery hook to ensure that my query was only sent upon clicking the button. However, a major drawback is that my component re-rend ...

Several arrays within the filteredData (MatTableDataSource) are being utilized

Hey there, I could really use some assistance. I have this data stored in a filteredData variable within a MatTableDataSource. filteredData My goal is to display this data in two separate tables, but I'm encountering issues where nothing is being sh ...