Retrieving information from the sessionStorage within app.module.ts

During the initialization of my application, it automatically redirects to the Login component. Here, I collect user data (username and password) and upon clicking the "Sign In" button, I send this information to the server. Upon receiving the Authorization key back from the server, I store it in the browser's sessionStorage.

this.http.post('/app/getUserByEmailAndPassword', userParams, {headers: this.headers}).subscribe(response => {
  if(response.status == 200){
     var data = response.json();
     sessionStorage.setItem('Authorization', data.authKey);
     this.userName = data.userName;
  } else {
     console.log("Error Occured While Logging In");
  }
})

In order to establish a WebSocket connection in my application, I am utilizing @stomp/ng-stomp. To ensure accessibility across all child components, I am configuring stomp in app.module.ts.

import { endponitConfig } from './../environments/endpoints';
import { NgModule, ApplicationRef } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
/*
 * Platform and Environment providers/directives/pipes
 */
import { routing } from './app.routing'
// App is our top level component
import { AppComponent } from './app.component';
import { APP_RESOLVER_PROVIDERS } from './app.resolver';
import { AppState, InternalStateType } from './app.service';
// Core providers
import {CoreModule} from './core/core.module';
import {SmartadminLayoutModule} from './shared/layout/layout.module';
import { ModalModule } from 'ngx-bootstrap/modal';
import { AuthGuard } from './+auth/+guards/index';
import { userRoleGuard } from './+auth/+guards/userRole.guard';
import { ChartModule } from 'angular-highcharts';
import * as SockJS from 'sockjs-client';
import {StompConfig, StompService} from '@stomp/ng2-stompjs';
import {} from 'jasmine';

export function socketProvider() {
  return new SockJS(endponitConfig.WEBSOCKET_URL);
}

const stompConfig: StompConfig = {
  url: socketProvider,
  headers:{
    AuthToken : sessionStorage.getItem('Authorization')
  },
  heartbeat_in: 0,
  heartbeat_out: 20000,
  reconnect_delay: 5000,
  debug: true
};
// Application wide providers
const APP_PROVIDERS = [
  ...APP_RESOLVER_PROVIDERS,
  AppState
];

interface StoreType {
  state: InternalStateType,
  restoreInputValues: () => void,
  disposeOldHosts: () => void
}

/**
 * `AppModule` is the main entry point into Angular2's bootstraping process
 */
@NgModule({
  bootstrap: [ AppComponent ],
  declarations: [
    AppComponent,
  ],
  imports: [ // import Angular's modules
    BrowserModule,
    BrowserAnimationsModule,
    FormsModule,
    HttpModule,
    ChartModule,
    ModalModule.forRoot(),
    CoreModule,
    SmartadminLayoutModule,
    routing
  ],
  exports: [
  ],
  providers: [ // expose our Services and Providers into Angular's dependency injection
    // ENV_PROVIDERS,
    AuthGuard,
    userRoleGuard,
    APP_PROVIDERS,
    StompService,
    {
      provide: StompConfig,
      useValue: stompConfig
    }
  ]
})
export class AppModule {
  constructor(public appRef: ApplicationRef, public appState: AppState) {}
}

When examining the stompConfig object,

const stompConfig: StompConfig = {
  url: socketProvider,
  headers:{
    AuthToken : sessionStorage.getItem('Authentication')
  },
  heartbeat_in: 0,
  heartbeat_out: 20000,
  reconnect_delay: 5000,
  debug: true
};

I encountered an issue where the Authorization token was returning null while trying to connect to sockjs. The Login component is nested within app.component.ts.

Is there a method to access sessionStorage data within app.module.ts? Can we utilize observables for this purpose, and if so, how?

Answer №1

To establish a global variable, it is recommended to utilize a service for this purpose. Within the service, you can implement the following logic:

stompConfig:StompConfig;
flag=false;

retrieveStomp(): any {
    if (flag) {
        return stompConfig;
    }
    else {
        if (sessionStorage.getItem('Authentication') != null) {
            this.stompConfig = {
                url: socketProvider,
                headers: {
                    AuthToken: sessionStorage.getItem('Authentication')
                },
                heartbeat_in: 0,
                heartbeat_out: 20000,
                reconnect_delay: 5000,
                debug: true
            };
            flag=true;

            return stompConfig;
        }
        else { return null; }
    }
}

You can then invoke the retrieveStomp function from your component to access the object.

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

Exploring the capabilities of the Angular 2 expression parser alongside the functionality of the

Is there a way to create an equivalent of the Angular 1.x ngInit directive in Angular 2? I am familiar with the ngOnInit hook, which is recommended for initialization code. The ngInit directive seems like a quick and declarative way to prototype or fix a ...

Guide to integrating a Jquery third-party plugin in Angular 7

Recently, I integrated jQuery and a third-party plugin called "stiffChart" into my Angular 7 project. After installing jQuery and the plugin in my project, I declared them in angular.json file as well. However, when trying to call a method from the plugin, ...

The functionality of the String prototype is operational in web browsers, but it encounters issues

Version: 8.1.0 The prototype I am working with is as follows: String.prototype.toSlug = function () { return (<string>this) .trim() .toLowerCase() .replace(/\s+/g, '-') .replace(/[^\w\-]+/g, '') ...

A guide on incorporating JavaScript variables within a GraphQL-tag mutation

I'm having trouble consistently using javascript variables inside graphql-tag queries and mutations when setting up an apollo server. Here's a specific issue I've encountered: gql` mutation SetDeviceFirebaseToken { SetDeviceFirebaseTok ...

Challenge encountered with asynchronous angular queries

Dealing with asynchronous calls in Angular can be tricky. One common issue is getting an array as undefined due to the asynchronous nature of the calls. How can this be solved? private fetchData(id){ var array = []; this.httpClient.get('someUrl ...

Saving a JSON object to multiple JSON objects in TypeScript - The ultimate guide

Currently, I am receiving a JSON object named formDoc containing data from the backend. { "components": [ { "label": "Textfield1", "type": "textfield", "key": "textfield1", ...

Angular Material design failing to display properly

Despite following the Angular Material guide on their website, I am still unable to see the gestures and design properly. I have meticulously followed all the steps outlined in the Angular Material guide. HTML <mat-radio-group> <mat-radio-but ...

Bringing in a TypeScript module to an Angular component

Having trouble with including a specific library in my component Here is the code for my component which uses geolib as the library: import { Component, OnInit } from '@angular/core'; import { StationsService } from '../../../services/stati ...

What is the best way to parse JSON data with Typescript?

I am dealing with JSON data structured as follows: jsonList= [ {name:'chennai', code:'maa'} {name:'delhi', code:'del'} .... .... .... {name:'salem', code:'che'} {name:'bengaluru' ...

The TypeScript `unknown` type restricts the use of non-unknown types in function parameters

Why is there an error in this code? const x: unknown[] = ['x', 32, true]; // OK const y: (...args: unknown[]) => unknown = (xx: number) => {}; // ERROR // Type '(xx: number) => void' is not assignable to type '(...args: u ...

What is the method for obtaining the total row of an ngFor loop within an HTML file?

I am trying to figure out how to retrieve the total number of rows in an ngFor loop and display it above. Any suggestions? <p>Total row: "I need to display the number of rows here"</p> <table class="table" > &l ...

Organizing JSON keys based on their values using Typescript

In the context of a main JSON structure represented below, I am interested in creating two separate JSONs based on the ID and Hobby values. x = [ {id: "1", hobby: "videogames"}, {id: "1", hobby: "chess"}, {id: "2", hobby: "chess ...

Tips for positioning a mat-form-field beside an h1 tag

I've been attempting to place an h1 next to a mat-form-field from Angular Material, but I'm encountering some difficulties. Here's what I've attempted so far: <div class="mat-elevation-z8"> <mat-form-field> <mat-l ...

Error message 'Module not found' occurring while utilizing dynamic import

After removing CRA and setting up webpack/babel manually, I've encountered issues with dynamic imports. https://i.sstatic.net/CRAWr.png The following code snippet works: import("./" + "CloudIcon" + ".svg") .then(file => { console.log( ...

Issue: Module "mongodb" could not be found when using webpack and typescript

I am encountering an issue while trying to use mongoose with webpack. Even though I have installed it as a dependency, when attempting to utilize the mongoose object and execute commands, it gives me an error stating that it cannot find the "." Module. Thi ...

Combining marker, circle, and polygon layers within an Angular 5 environment

I am working on a project where I have an array of places that are being displayed in both a table and a map. Each element in the table is represented by a marker, and either a circle or polygon. When an element is selected from the table, the marker icon ...

How to store an imported JSON file in a variable using TypeScript

I am facing a challenge with a JSON file that stores crucial data in the following format { "login": { "email": "Email", "firstName": "First name", "lastName": "Last name", ...

The issue of Rxjs Subject in Angular2 running twice persists even after unsubscribing

Currently, I am developing a desktop application using angular2 and electron with a download feature integrated within it. The code for my DownloadService looks like this: import {Injectable} from '@angular/core'; import {Subject} from "rxjs"; ...

Encountering difficulties retrieving information from an API using Angular

I am encountering an issue while trying to retrieve data from an API. When I use console.log() to view the data, it shows up in the console without any problem. However, when I attempt to display this data in a table, I keep receiving the error message: ER ...

Experiencing a useContext error when implementing MDX with NextJS 13

I am currently working on integrating mdx files into Next.js 13. After completing all necessary configurations in next.config and creating the file structure, I have the following path within the app folder: > docs > components > accordion > pa ...