Getting the value from the localStorage object key in Angular: a step-by-step guide

Looking for assistance here. Within the localStorage, I have an object as shown in the example below. My framework of choice is Angular, and I'm trying to retrieve the value associated with the first linkedinMail key. Despite my attempts using different approaches, the console output only shows the opening curly brace {

Object stored in localStorage:

{"linkedinMail": "mail.com", "password": "123"}

First approach:

public linkedinEmailBody: any

const emailLoginLinkedin = localStorage.getItem('credsForJetLeadBE')
let [key, value] = Object.entries(emailLoginLinkedin)[0];
this.linkedinEmailBody = value;
console.log(this.linkedinEmailBody) // result: `{`

Second approach:

public linkedinEmailBody: any

const emailLoginLinkedin = localStorage.getItem('credsForJetLeadBE')
const valueEmailLinkedin = Object.values(emailLoginLinkedin)[0];
this.linkedinEmailBody = valueEmailLinkedin
console.log(this.linkedinEmailBody) // result: `{`

Third approach:

public linkedinEmailBody: any

const emailLoginLinkedin = localStorage.getItem('credsForJetLeadBE')
const valueEmailLinkedin = emailLoginLinkedin[Object.keys(emailLoginLinkedin)[0]];
this.linkedinEmailBody = valueEmailLinkedin
console.log(this.linkedinEmailBody) // result: `{`

When employing standard JavaScript, I am able to retrieve the correct value for the linkedinMail field instead of just the opening brace {. What could be going wrong in my Angular implementation? Appreciate your help.

Answer №1

tag, it is important to note that LocalStorage and sessionStorage store strings by default. To convert these stored strings back to their original type, you will need to parse them using JSON.parse(). For example:

const emailLoginLinkedin = JSON.parse(localStorage.getItem('credsForJetLeadBE'));

Once parsed, you can then extract and utilize the first key-value pair in any desired manner.

Answer №2

To retrieve the actual object from local storage, you must convert the stored value from a string using:

JSON.parse(localStorage.getItem('credsForJetLeadBE'))

This method will return the desired object.

Try this code snippet:

const emailLoginLinkedin = JSON.parse( // (1)
    localStorage.getItem("credsForJetLeadBE")
);

let [key, value] = Object.entries(emailLoginLinkedin)[0];
let linkedinEmailBody = value;
console.log(linkedinEmailBody);
  1. The data in local storage is stored as a JSON string representing the object being saved.

    Using JSON.parse(), JavaScript can interpret it as an object for manipulation.

Answer №3

Let me provide you with a comprehensive example, as the issue could arise not only in the GET method but also in the SET method.

I prefer not to take the "easy way" approach so that you can grasp the concept better. Once everything is working smoothly, you can explore more complex options like destructuring.

// Initial Declaration
interface IEmailLoginLinkedin = {
   linkedinMail: string; 
   password: string;
}

emailLoginLinkedin: IEmailLoginLinkedin;

// Initialization
 this.emailLoginLinkedin =  { linkedinMail: 'example@mail.com',password: 'password123' };

// Set value
this.setEmailLoginLinkedin(this.emailLoginLinkedin);

// Get values
const emailLoginLinkedinObject: IEmailLoginLinkedin|null  = this.getEmailLoginLinkedin();

let linkedinMail: string;
let password: string;

if (emailLoginLinkedinObject) {

   linkedinMail= emailLoginLinkedinObject.linkedinMail;
   password = emailLoginLinkedinObject.password;

   // Alternatively, you can use 'destructuring':({linkedinMail, password}) = emailLoginLinkedinObject;

} else {
console.log('emailLoginLinkedin data is not available in the localStorage');
}

Here are the methods for accessing the localStorage:

 
// Serialize and STORE the emailLoginLinkedin in localstore:
setEmailLoginLinkedin(emailLoginLinkedin: IEmailLoginLinkedin){
   const emailLoginLinkedinString:string = JSON.stringify( emailLoginLinkedin );
   localStorage.setItem('emailLoginLinkedin', emailLoginLinkedlinString);
}

----
 
// READ the emailLoginLinkedin from localstorage and Deserialize
getEmailLoginLinkedin(): IEmailLoginLinkedin|null {
 
   const emailLoginLinkedinString:string|null =  localStorage.getItem('emailLoginLinkedin');
 
   if( emailLoginLinkedinString ){
       return JSON.parse(emailLoginLinkedinString);
   } else {
       return 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

Create a 3D visualizer on my site using various images of the object from multiple perspectives

Looking to incorporate a 3D object into my website, but the file size is too large. I'm considering taking images of the object from various angles and utilizing code to create a visual 3D effect when users interact with them. I was inspired by a web ...

Anticipating the completion of multiple observable subscription functions

Is there a way to replace and convert all words in an array using an object's method that returns an observable? I found a helpful solution on this post which uses bind to pass the correct value. After all subscriptions are complete, I want to execut ...

Creating a function to filter an array of objects based on specific properties and values in JavaScript

How can you compare arrays of objects with arrays using JavaScript? I am looking to evaluate an array of objects based on specific conditions. If the targetvalue is the same and the code value is not present in the arraylist, return the array of object ...

Determine image size (pre-upload)

One of the requirements for a project I am working on is to verify the dimensions (width and height) of images before uploading them. I have outlined 3 key checkpoints: 1. If the dimensions are less than 600 X 600 pixels, the upload should be rejected. ...

Learn how to extract values from an object in Vue JS time-slots-generator and display either PM or AM based on the

Using the time-slots-generator package, I am able to display the time from 0:15 to 24:00. However, the issue is that this package does not have built-in functionality to display AM/PM, so I had to create a manual solution for it. To achieve this, I modifi ...

Form validation is an essential feature of the Angular2 template-driven sub form component

I'm currently working on a template-driven form that includes a group of inputs generated through an ngFor. My goal is to separate this repeating 'sub-group' into its own child component. However, I'm encountering difficulties in ensur ...

AngularJS unable to redirect form action

<head> <title>Authentication</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script> </head> <body> <form> <p>Username:<br> ...

Challenges in decoding %20 characters in URLs

In my experience, I've come across a helpful thread that explains how to create permalinks or pass string values via a URL in a very practical manner: Original Thread However, it seems that the above-mentioned thread does not address decoding white ...

Guide on positioning an image in the upper right corner of another

Does anyone know how to use JavaScript to display one image in the top right corner of another image? I attempted to achieve this by using the appendChild() method to add the image element, but it doesn't seem to be working. function appendImage(ele ...

Separate the navbar-brand and nav-items onto separate lines within the Bootstrap 4 navbar

I would like to arrange the navbar-brand and nav-items on separate rows. Put the navbar brand on the first row and the navigation items on the second row Existing code: <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="nav ...

Merging values of different keys in a .json file

Check out my json file below: { "foo": "https://3a1821d0.ngrok.io/api/foo", "bar": "https://3a1821d0.ngrok.io/api/bar", } I am interested in changing the key 3a1821d0 to a different variable within the json structure, like so: { "some_variab ...

I am facing an issue with React Native where I cannot read the property 'push' as it is showing undefined. This problem occurred while using NavigatorIOS and trying

I have been working on a react native application and I am currently facing an issue with routing the user to the next view after they successfully log in through Facebook. The error message "Cannot read property 'push' of undefined" keeps appea ...

Distinguishing Jquery and Ajax

Could someone kindly provide a comparison of the distinctions between Jquery and Ajax? ...

Navigating to the desired page in node.js

Currently, I am dealing with Node.js servers and encountering an issue where the server only serves a single file regardless of the URL path specified. I understand that by writing a file, I can have the server display that particular page every time you l ...

Utilizing Media Queries with Dynamic Vue Properties

On one of my website pages, I always have a Div element with a Background Image that changes based on Media Queries (for example, I fetch a smaller resolution from my CDN on mobile phones). However, since I retrieve the Image URL on Page Load, I need to s ...

Error encountered when trying to populate the second dropdown in the change event

Having some difficulty with populating a second dropdown from a mysql result. The code seems fine, but there must be something off. The value being passed correctly to $rtvcompany = $_GET['rtvcompany']; from loadboxRtvaddr.php?rtvcompany= in PHP ...

Mobile-friendly Angular 2 material tables for optimal viewing on all devices

I'm currently in the process of incorporating datatables into my Angular 4 project using Angular Material datatables (https://material.angular.io/). Everything appears to be functioning properly UNTIL I switch to a mobile view, at which point the ent ...

Troubleshoot: Angular hide/show feature malfunctioning

I am facing an issue where clicking on one parent element causes all parent elements to show or hide their child elements accordingly. I am relatively new to Angular 2 and would appreciate any recommendations. Below, you can see the code for the component ...

.js file paths in nested web pages using .net MVC4

I'm facing an issue with my MVC4 application. I have set up a masterpage with "bundleconfig" to manage CSS and JS files. Everything seems to be working fine, for example when I access "localhost1234:/Admin/Index" everything displays correctly. However ...

The intersectObjects function is failing to retrieve the object from the OBJMTLLoader

Within my scene, I've introduced a new object along with several other cubes. To detect collisions, I'm utilizing the following code snippet that fires a Ray: var ray = new THREE.Raycaster(camera.position, vec); var intersects = ray.intersectObj ...