Using Angular2, assign a value to the session and retrieve a value from the session

I am having trouble getting and setting a session. Here is my code:

login_btnClick() {

        var NTLoginID = ((document.getElementById("NTLoginID") as HTMLInputElement).value);
        this._homeService.get(Global.BASE_USER_ENDPOINT + '/EmployeeDetailsApi?user_id=' + NTLoginID)
            .do(data => sessionStorage.setItem('session',JSON.stringify(data)))
            .subscribe(homes => { this.homes = homes; this.indLoading = false; },
            error => this.msg = <any>error);
        var session = sessionStorage.getItem('session');
        alert(JSON.stringify(session));
        this.router.navigateByUrl('/user');
    }

I keep receiving only null instead of the actual value. I can see the value from

.do(data => alert(JSON.stringify(data)))
. As a newcomer to angular2, I would appreciate any assistance.

Answer №1

When working with Http requests in Angular 2 (or any other framework), it's important to remember that these requests are asynchronous. This means that once your code hits the .do() method, it doesn't wait for the response before moving on to the next line of code. To address this issue, you can modify your code like so:

this._homeService.get(Global.BASE_USER_ENDPOINT + '/EmployeeDetailsApi?user_id=' + NTLoginID)
    .do(data => sessionStorage.setItem('session',JSON.stringify(data)))
    .subscribe(homes => { 
          this.homes = homes;
          this.indLoading = false; 
          var session = sessionStorage.getItem('session');
          alert(JSON.stringify(session));
          this.router.navigateByUrl('/user');
    },
    error => this.msg = <any>error);

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

How can RootStateOrAny be turned off in React with typescript?

Whenever I need to employ useSelector, I find myself repeating this pattern: const isLoading = useSelector( (state) => state.utils.isLoading ); Is there a shortcut to avoid typing out RootStateOrAny each time? It's starting to become a hassl ...

What steps are needed to generate a production version of a TypeScript monorepo application that can be deployed to an Azure Function App?

I've been grappling with understanding Typescript project references and their intended use in a production build, especially for an Azure Function App. I'm not utilizing any monorepo functionality at the package manager level, such as npm worksp ...

Learn the process of invoking Firebase Functions through AngularFire

My project involves creating a Firebase Cloud function using functions.https.onRequest to act as an API that returns JSON data from the Firebase Realtime database. After some research, I discovered functions.https.onCall, which provides authentication fun ...

Why isn't the constraint satisfied by this recursive map type in Typescript?

type CustomRecursiveMap< X extends Record<string, unknown>, Y extends Record<string, unknown> > = { [M in keyof X]: M extends keyof Y ? X[M] extends Record<string, unknown> ? Y[M] extends Record<st ...

ESLint has issued a warning indicating that the selector must be utilized as an element

Running Angular 12 and ESLint together has raised some issues for me. Whenever I run ng lint, ESLint reports a problem with the selector below. 10:13 error The selector should be used as an element (https://angular.io/guide/styleguide#style-05-03) @an ...

Unable to assign a default value to an Angular input field

My web page utilizes an Angular form to display user data fetched from a MongoDB database. The information includes the user's name, phone number, email, etc. I want the default value of the input field to be set as the placeholder text, allowing user ...

Error when accessing JSON property in Angular with Ionic 2: A Strange TypeError

I have implemented a provider in my Ionic project to fetch the user object from storage. Below is the code: import { Injectable } from '@angular/core'; import { Storage } from '@ionic/storage'; @Injectable() export class ApiProvider { ...

The element 'md-chips' from Angular2 material is unrecognized

I am currently developing an Angular2 application utilizing @angular/material 2.0.0-beta.2 and I am facing a challenge in implementing Chips, as I keep receiving the error message 'md-chips' is not a known element. Here are the steps I have taken ...

The TS2339 error has occurred because the "email" property cannot be found on the specified "Object" type

I encountered an issue while using Angular 5, here is the code snippet : signIn(provider) { this._auth.login(provider).subscribe( (data) => { console.log(data); this.hideForm = false; this.emaill = data.email; ...

Creating a unified deployable package for a Spring Boot Rest service and an Angular App in a single war file

Currently dealing with a scenario where I find myself needing to deploy a single war file containing an Angular application that consumes a REST API also located within the same war file. The issue arises when CORS errors occur while trying to communicate ...

What is the best way to arrange map elements in a React application?

I am trying to implement filter buttons for low to high rates and high to low rates, but I am having trouble figuring it out. How can I apply the filter to display the data accordingly? The data that needs to be filtered is stored in rate.retail_rate. ty ...

Guide to Implementing Kendo-Grid in Angular 4 CLI

Having trouble using the Kendo-Grid in Angular4? You may encounter this error message: Uncaught Error: Template parse errors: 'Kunden-grid' is not a known element: 1. If 'Kunden-grid' is an Angular component, then verify that it is par ...

Clicking on a single checkbox causes the entire input to become deactivated due to the way the system is

I'm encountering a puzzling issue that has me feeling like I know the solution, yet I don't. I set "State" to [checked]. The problem arises when, upon turning it into a map and clicking just one checkbox, the entire selection is clicked. To addre ...

Can you explain the mechanics behind the functionalities of @angular and @type dependencies?

This inquiry may have been raised before, but I couldn't uncover all the solutions. If that's the case, my apologies. I have a good grasp on how package.json and dependencies / dev-dependencies function in Node applications. Currently delving i ...

Adding form input fields in real-time by clicking the add button

Currently, I am looking to develop a party hosting application using Ionic 2. My main goal is to have the ability to add form input fields for guests dynamically by clicking on an "add" button. Do you have any suggestions on how this can be achieved in I ...

Using Angular template to embed Animate CC Canvas Export

Looking to incorporate a small animation created in animate cc into an angular template on a canvas as shown below: <div id="animation_container" style="background-color:rgba(255, 255, 255, 1.00); width:1014px; height:650px"> <canvas id="canv ...

Cypress: Importing line in commands.ts is triggering errors

After adding imports to the commands.ts file, running tests results in errors. However, in commands.ts: import 'cypress-localstorage-commands'; /* eslint-disable */ declare namespace Cypress { interface Chainable<Subject = any> { c ...

Learn a simple method for converting or assigning an Observable to a Behavior Subject, allowing for seamless sharing between components

As a newcomer to Observable style programming, I have encountered a challenge regarding sharing user information across various components in my Angular app. My approach involves using BehaviorSubject to share this data, drawing inspiration from the concep ...

Showing canvas lines while dragging (using only plain JavaScript, with React.JS if needed)

Is there a way to add lines with two clicks and have them visible while moving the mouse? The line should only be drawn when clicking the left mouse button. Any suggestions on how I can modify my code to achieve this functionality? Currently, the lines are ...

What is the best way to account for the 'elvis operator' within a given expression?

When connecting to my data from Firebase, I noticed that using the elvis operator is essential to avoid encountering undefined errors. Recently, as I delved into creating reactive forms, I encountered an issue with a component I developed that fetches actu ...