What is the best way to save a string for future use in Angular after receiving it from a POST request API?

I have been assigned to a project involving javascript/typescript/angular, even though I have limited experience with these technologies. As a result, please bear with me as I may lack some knowledge in this area. In the scenario where a user logs in, there is a post method api call that assigns the user session and returns a sessionId as a string upon successful completion. My objective is to understand how to fetch and save this string for future use within my application, particularly as a parameter for different api calls. Below is my existing service configuration:

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

Could you provide guidance on how to access and retain the returned string?

Answer №1

To ensure that the sessionId remains intact even after a browser reload, you can store the id in the browser's localStorage.

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

You can easily retrieve the value anywhere by using:

localStorage.getItem("sessionId");

If this approach doesn't fit your requirements, consider creating a service with getters and setters to manage app configuration data.

Example of an 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 the AppDataStore into any component/service to set and retrieve the sessionId using the provided getter and setter methods.

For instance,

In any-component.ts/any-services.ts:

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


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

Similarly, to access the sessionId in another file, simply inject the AppDataService in the constructor and retrieve the sessionId like this:

this.appDataStore.sessionId;

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

Utilizing jQuery to Extract Values from a List of Options Separated by Commas

While usually simple, on Mondays it becomes incredibly challenging. ^^ I have some HTML code that is fixed and cannot be changed, like so: <a class="boxed" href="#foo" rel="type: 'box', image: '/media/images/theimage.jpg', param3: ...

I'm encountering an issue where Typescript is unable to locate the Firebase package that I

I have a TypeScript project that consists of multiple .ts files which need to be compiled into .js files for use in other projects. One of the files requires the firebase package but it's not being found. The package is installed and located inside t ...

Encountering issues when trying to build a Nestjs app with node-crc (rust cargo) in Docker

I am encountering an issue with building my Nest.js app using Docker due to a dependency called "node-crc" version "2.0.13" that fails during the docker build process. Here is my Dockerfile: FROM node:17.3.1-alpine RUN curl https://sh.rustup.rs -sSf | sh ...

Safari browser removes spaces after commas in cookie values

I'm encountering an issue when trying to set a session cookie for storing an Address. It seems that whenever I include a comma followed by a space in the cookie's value, Safari automatically removes the spaces after the commas, causing the format ...

Prepending the emulated prefix to Angular 6-7 ViewEncapsulation

Can we customize the tags generated when using ViewEncapsulation.Emulated in an Angular 2-7 component? Currently, it generates tags like [_ngContent-C0], but is there a way to add a custom string to the generated tag, such as [_ngContent-C0-myApp]? Thank ...

Tips for sending a file rather than a json object in nextjs

Is there a way to send a file from either route.ts or page.ts, regardless of its location in the file-system? Currently, I am using the following code in my back-end python + flask... @app.route("/thumbnail/<string:filename>") def get_file ...

Issue encountered with TypeORM and MySQL: Unable to delete or update a parent row due to a foreign key constraint failure

I have established an entity relationship between comments and posts with a _many-to-one_ connection. The technologies I am utilizing are typeorm and typegraphql Below is my post entity: @ObjectType() @Entity() export class Post extends BaseEntity { con ...

Process executes another process

Can anyone assist me with a JavaScript inquiry? I am curious if it is feasible to implement this: variable: { info1: 'info1', info2: 'info2', show: false, someNameFunction: functionWhichIWantRun(row) } So, after defining the var ...

Discover the simplicity of incorporating pagination into an HTML table with Angular Material

My goal is to implement pagination on my webpage, displaying 3 rows per page and enabling navigation through pages using Angular Material pagination. In usersComponent.ts, I retrieved data from an API: import { Component, OnInit, ViewChild } from '@an ...

Incorporating a new attribute into the JQueryStatic interface

I am trying to enhance the JQueryStatic interface by adding a new property called someString, which I intend to access using $.someString. Within my index.ts file, I have defined the following code: interface JQueryStatic { someString: string; } $.s ...

Transforming jQuery into Angular - Press Button to update choices in Dropdown List

I am looking to integrate some AngularJS features into a website that currently utilizes jQuery. Here is the issue I am facing: With jQuery, clicking a button triggers a dropdown item change. Please refer to the jsfiddle below for an example: $('# ...

Utilize the identical ReactJS hook across multiple components

I've created a hook that pulls data from an API and stores the result in my component's state using setAllCommunitiesFromSponsor. Now I want to use this same hook in another component. Instead of copying and pasting, what is the best way to imp ...

Accessing information from req.files in a TypeScript environment

I am currently using multer for uploading images. How can I retrieve a specific file from req.files? Trying to access it by index or fieldname has been unsuccessful. Even when I log it, I see that it's a normal array, so I suspect the issue may be rel ...

Attributes of an object are altered upon its return from a Jquery function

After examining the following code snippet: index.html var jsonOut = $.getJSON("graph.json", function (jsonIn) { console.log(jsonIn); return jsonIn; }); console.log(jsonOut); The graph.json file contains a lengthy JSON fo ...

Refresh database post drag and drop operation

I am seeking a way to update a "state" SQL row after dragging an element between the "DZ", "WT", and "ZK" divs. Below is a snippet of my code: SQL queries: $sql = "select * from tasks where login = '$user_check' AND state = 1"; $sqlDodane = mys ...

Storing a dynamically created grid of inputs using a consistent ng-model

I have the following code snippets: $scope.createPack = function(informationsPack, informationsActivite) { PackService.add(informationsPack, informationsActivite) .then(function(res) { $state.go(&apos ...

Locating discord.js users who possess multiple roles

Here is my code in its entirety as I have received some confusion on other forums: I am working on creating a Discord bot that can list users with a specific role. The plan is to create an array of roles, compare user inputs to the array, and display user ...

Determining the total number of combinations possible from a collection of five arrays containing items

I have five massive collections filled with various strings, and each of them contains a different number of elements. Below are examples of the lists: List 1 "Jeffrey the Great", "Bean-man", "Joe", "Charles", "Flamur", "Leka", ...

Why does the React input value keep its value when the modal is re-rendered, despite the state being updated correctly?

Take a look at this sandbox link for the code snippet: Sandbox Showcased below is a table structure: https://i.sstatic.net/3F3Mc.png By clicking on the 'edit' button, a modal window opens up as shown below allowing you to edit input fields (onC ...

Failing to hide a div on hover: Hoverintent's shortcomings

When I hover over the div with the unique identifier id="navbar", it doesn't seem to trigger any actions. I have included the following script in my document head: <script type="text/javascript" src="https://ajax.googleapi ...