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 I make angular material data table cells expand to the full width of content that is set to nowrap?

This example demonstrates how the mat-cells are styled with a specific width: .mat-cell { white-space: nowrap; min-width: 150rem; } If the width is not specified, the table will cut off the text due to the white-space property being set to nowrap. Is ...

Next.js does not support tooltips with custom children components

I created a unique Tooltip component and I'm attempting to include NextLink as the children. However, I encountered an error similar to the one below. Warning: Failed prop type: Invalid prop `children` supplied to `ForwardRef(Tooltip)`. Expected an e ...

Tips on utilizing a function that was generated within the constructor

I'm currently in the process of developing a function within the constructor, and it is essential that this function be placed inside the constructor. I am interested in implementing a button to trigger this function from an external source, but unfor ...

Issue with Angular 6.1.0: Scroll position restoration feature malfunctioning

RouterModule.forRoot(routes, { scrollPositionRestoration: 'enabled' }) In the latest version 6.1.0, there is a new feature that aims to restore the scroll position after navigation. Unfortunately, I encountered an issue where the scroll restorat ...

Arranging Angular Cards alphabetically by First Name and Last Name

I am working with a set of 6 cards that contain basic user information such as first name, last name, and email. On the Users Details Page, I need to implement a dropdown menu with two sorting options: one for sorting by first name and another for sorting ...

Here's a new take on the topic: "Implementing image change functionality for a specific div in Angular 8 using data from a loop"

I need to create a list with dynamic data using a loop. When I click on any item in the list, I want the image associated with that item to change to a second image (dummyimage.com/300.png/09f/fff) to indicate it's active. This change should persist e ...

Tips for modifying the text color of a div that is being iterated through using ngFor

I am facing an issue with a div that is being looped using ngFor. What I want to achieve is when a user clicks on one of the divs in the loop, only that particular div should change its text color. If another div is clicked, it should change color while th ...

Resolving NestJS Custom Startup Dependencies

In my setup, I have a factory responsible for resolving redis connections: import {RedisClient} from "redis"; export const RedisProvider = { provide: 'RedisToken', useFactory: async () => { return new Promise((resolve, reject ...

Unable to input text in an Angular2 input field

Encountering an issue with users on Windows 7 using IE11 while trying to input information into textboxes or textareas. The drop-downs and checkboxes are functioning properly, but additional fields cannot be filled out even after toggling visibility with t ...

Switching from callback to function in TypeScript

Currently, I am utilizing the mongodb driver to establish a connection with mongo: public listUsers(filterSurname?:string):any { if (this.connected) { debug.log(this.db); var results; this.db.collection(' ...

Having trouble converting the response into a valid TypeScript value for storage

These are the interfaces I have described: enum ProductType {current, closed, coming} export interface CurrentProductForCarousel { type_product:ProductType.current; offers: ProductMainInfo[] } export interface ProductMainInfo { id: number; disclai ...

Steps for converting a tsx file into a js file in React

Currently, I am in the process of a React Project and have numerous tsx files that I aim to convert for utilization as JavaScript within my project. What would be the best approach to achieve this task? ...

Simple steps to make an Angular Material mat-card expand to full screen

Currently, my goal is to create a portal-style page layout using Angular Material. This layout will feature a grid of cards where each card can be expanded to take up the majority of the visible page, covering all other cards that are not in focus. The car ...

Using TypeScript in combination with Angular for implementing CORS protocol

As I try to send a request to my REST endpoint, the following code is executed: this.http.request(path, requestOptions); The path is set to: http://localhost:8082/commty/cmng/users and the requestOptions are as follows: { headers: { user: "sdf", pas ...

Designing Angular 1 table row components with future migration to Angular 2 in consideration

Issue with AngularJS nested directives placement outside parent element Encountering the same challenge in my project using Angular 1.4, but I am also aiming to construct the rows as Angular 2 components which prevents me from using "replace: true". I am ...

The type '{ componentParent: this; }' does not share any properties with the type 'Partial<RegisterEnterpriseComponent>' in Angular

Currently working with angular 10, attempting to display a modal in my component, however encountering the following error: The type '{ componentParent: this; }' has no properties in common with the type 'Partial<RegisterEnterpriseCompone ...

Navigating a SwipeableDrawer in React with scrolling functionality

I'm currently using a swipeable drawer in React from MUI to display lengthy content. My goal is to keep the title visible even when the drawer is closed, and I was able to achieve this through the following method: MUI SwipeableDrawer I've provi ...

An effective way to apply Bootstrap styles to projected content within an Angular 7+ application

Although Angular content projection documentation is lacking, I have successfully implemented content projection. However, I am unsure of how to pass Bootstrap classes down to the projected content <ng-content></ng-content> in the child compone ...

Having trouble with the Angular router link suddenly "failing"?

app.routes.ts: import { environment } from './environment'; import { RouterModule } from "@angular/router"; import { ContactUsComponent } from './static/components/contact-us.component'; import { HomeComponent } ...

Eliminating data type from union in Typescript

I have a specific type that I collect from various other types: type CustomType = { id: string; foo: (string | Type1)[]; bar: (string | Type2)[]; baz: string | Type3 | null; description: string | null; } I am interested in refining thi ...