How to store a string for later use in Angular from a post method api call?

こ雲淡風輕ζ 提交于 2020-07-10 07:33:31

问题


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?


回答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;


来源:https://stackoverflow.com/questions/61918572/how-to-store-a-string-for-later-use-in-angular-from-a-post-method-api-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!