简体   繁体   中英

Getting data from sessionStorage in app.module.ts

In my application, whenever the app is loaded. First it redirects to Login component where I'm taking the data from the user (username and password) and in "Sign In" button click. I am sending the username and password to the server and getting back the Authorization key that is I am setting it into the sessionStorage of my browser.

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");
  }
})

I am using @stomp/ng-stomp for the Websocket connection in my application. Now my requirement is, I am configuring stomp in app.module.ts so that it will be accessible to all the other child components.

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) {}
}

Now if you look at stompConfig object

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

I have to use the Authorization token here while connecting to the sockjs but it returns null when I am getting back the data from session storage. I have the login component as a child component of app.component.ts .

So, is there any way to get the data from sessionStorage in app.module.ts .

Can we make it observable, if yes then how?

You should use a service to set a global variable. You can do the following in a service:

stompConfig:StompConfig;
flag=false;

getStomp(): any {
    if (flag) {
        return stompConfig;
    }
    else {
        if (sessionStorage.getItem('Authentication') != null) {
            this.stompConfig: 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; }
    }
}

And call this function from your component to get the object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM