0

I was put into a project where I have little experience with javascript/typescript/angular, so please excuse my ignorance. When a user logs in I have a post method api call that adds the user session and on a successful post it returns the sessionId which is a string. I need to know how to retrieve and store that string for later use in my application which will be used as a parameter for a couple different api calls. Here is my current service setup:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { catchError, retry } from 'rxjs/operators';
import { ConfigService } from './../config/config.service';
import { UserSession } from './user-session.interface';
import { ApiServiceBase } from '../shared/api-service-base'

@Injectable({
  providedIn: 'root'
})

export class UserSessionService extends ApiServiceBase {

  public userSession: UserSession;
  private apiRoute: string = 'user-session';

  constructor(http: HttpClient, configService: ConfigService) {
    super(http, configService);
  }

  public async AddUserSession(userName: string): Promise<string> {
    this.appSettings = (await this.configService.loadConfig().toPromise());
    this.userSession = { userName: userName, application: this.application};
    return this.http.post<string>(this.appSettings.apiSetting.apiAddress + this.apiRoute, this.userSession)
      .pipe(
        retry(1),
        catchError(this.handleError)
      )
      .toPromise()
  }
}

How can I retrieve and store the returned string?

JCA
  • 197
  • 2
  • 2
  • 16
  • You could use the example of [component interaction via a service](https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service) to store the string on something like a Subject or BehaviorSubject that can be subscribed to. Maybe start with that and update your question if you continue having issues. – Alexander Staroselsky May 20 '20 at 17:16
  • In terms of Subject vs BehaviorSubject, BehaviorSubject can emit the last emitted value when consumers subscribe to it. Check out this question about getting the value: https://stackoverflow.com/questions/37089977/how-to-get-current-value-of-rxjs-subject-or-observable . Also you don't need to use promises, you can use operators such as switchMap or mergeMap to "chain" async requests. – Alexander Staroselsky May 20 '20 at 17:22

1 Answers1

1

If the sessionId needs to be preserved even on browser reload, try storing the id in localStorage of the browser.

localStorage.setItem("sessionId", "123");

You can retrieve the value anywhere by simply using

 localStorage.getItem("sessionId");

However if thats not the case you can also have a service where u can have your getters and setters for setting and getting app config data

app-data.service.ts

@Injectable({
  providedIn: 'root'
})
export class AppDataStore {
   private _sessionId: string;
   get sessionId() {
       return this._sessionId;
   }

   set sessionId(sId){
        this._sessionId = sId
   }
}

You can inject AppDataStore in any component/service and set the sessionId using the setter and also you will be able to get the sessionId using the getter method.

For example,

any-component.ts/any-services.ts

constructor(private userSessionService : UserSessionService, private appDataService: AppDataStore){}


doSomething(){
   const sessionId = await this.userSessionService.addUserSession();
   this.appDataService.sessionId = sessionId
}

Similary in order to get the sessionId back in any other file , you can just inject AppDataService in the constructor of the class and read the sessionId back using

this.appDataStore.sessionId;
Shijil Narayanan
  • 1,011
  • 8
  • 21
  • I'm not sure how you are getting and setting data in the components. Can you share an example? – JCA May 20 '20 at 21:37