Convert an interface type variable to a string representation

I'm just starting to learn angular and I'm attempting to convert my response from an interface type into a string so that I can store it in session storage. However, when I try to save them, they are being stored as [object] in the session storage

Here is my code:


const loginResponse = await this.serverLoginSvc.login(this.serverData);
console.log(JSON.stringify(loginResponse.data));
sessionStorage.setItem('source_auth_data', JSON.stringify(loginResponse.data));

where loginResponse is of type

ApiResponseModel<AuthResponseModel>
interface

Please help me figure out what mistake I am making here

Answer №1

For further information on sessionStorage, please visit this link.

It is advisable to steer clear of asynchronous storage settings related to login procedures without full control over the response.

In this scenario, I recommend using a library that utilizes localStorage and indexedDB such as local-storage

You can implement it like so:

this.serverLoginSvc.login(this.serverData).subscribe(
  next: (response: ApiResponseModel<AuthResponseModel>) => {
    console.log(response);
    if (response !== undefined && response !== null) {
      this.storage.set('source_auth_data', response.data).subscribe(() => {
        // Perform actions here
      });
    }
  },
  error: error => {
    this.storage.delete('source_auth_data');
  }
);

Keep in mind that the login function should return an Observable.

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

Configuring CORS settings in Angular-cli

Upon making a request to my backend url http://docker-users:5500/users?all=true, which returns a list of users, I encountered an issue with Angular-CLI's localhost url: http://localhost:4200. Even after configuring the proxy.config.json file and addin ...

the process of altering properties in vue js

After running my Vue file, I encountered the following console error. As someone new to Vue programming, I'm attempting to utilize a Syncfusion UI component to display a grid. Prop being mutated: "hierarchyPrintMode" I am unsure where to add the comp ...

Notify user before exiting the page if there is an unsaved form using TypeScript

I am working on a script that handles unsaved text inputs. Here is the code for the script: export class Unsave { public static unsave_check(): void { let unsaved = false; $(":input").change(function(){ unsaved = true; ...

Receiving data from a service in Angular 2 with rxjs subscribe throws an error: it is not a

I've recently started working with Angular and I'm encountering an issue when trying to pass the _newArray to my child component using a shared service. Service fetchData(): Observable < any > { return forkJoin(this.fetchQuestions(), th ...

Implementing Routes in Express Using Typescript Classes

Seeking assistance in converting a Node.js project that utilizes Express.js. The objective is to achieve something similar to the setup in the App.ts file. In pure Javascript, the solution remains unchanged, except that instead of a class, it involves a mo ...

What is the best way to retrieve the 5 most recent posts for each genre using Laravel's API

In the process of developing an application (which is my academic project), I am utilizing Laravel 5.4 as my API combined with Angular 5. The focus of my project revolves around a music blog, necessitating specific features like categories and subcategorie ...

The reCAPTCHA feature in Next.js form is returning an undefined window error, possibly due to an issue with

Trying to incorporate reCAPTCHA using react-hook-form along with react-hook-recaptcha is posing some challenges as an error related to 'window' being undefined keeps popping up: ReferenceError: window is not defined > 33 | const { recaptchaL ...

Encountering ExpressionChangedAfterItHasBeenCheckedError in Angular 17 even after invoking detectChanges method

I'm encountering a minor problem with Angular and its change detection mechanism. I have created a simple form where additional input fields can be added dynamically. However, every time I click the add button, an ExpressionChangedAfterItHasBeenChecke ...

I need a way to call a function in my Typescript code that will update the total value

I am trying to update my total automatically when the quantity or price changes, but so far nothing is happening. The products in question are as follows: this.products = this.ps.getProduct(); this.form= this.fb.group({ 'total': ...

Retrieve the property of a Typescript object using a template argument

I am looking to develop a Typescript Collection class that can locate items by field. Here is an example of what I have in mind: class Collection<T, K keyof T> { private _items: T[]; public isItemInCollection(item: T) { return _item ...

Ways to showcase my select/option in Angular 14?

My select input is not displaying and I'm struggling to understand why. Despite seeing it in the inspector, it remains hidden... I initially attempted to retrieve data from my service, which failed. Then, I experimented with placing static data direc ...

When a model is changed from within a jQuery event, Angular 2 fails to update the view

During the development process, I encountered an issue while creating a custom search panel that displayed search results in a dropdown container. In my controller, I defined the following: export class ProductSearchComponent implements OnInit { publ ...

How can I adhere to Angular 2's naming convention for Input and Output as suggested by the styleguide?

Working with inputs and outputs while following Angular 2's styleguide naming convention Initially, my directive was defined like this: ... inputs: [ 'onOutside' ] ... export class ClickOutsideDirective { @Output() onOutside: EventEmitter ...

Unraveling the structural directive string syntax within our custom Angular directive: A step-by-step guide

As previously mentioned, I am interested in using the current string-based syntax for structural directives within a custom directive. <element *ngFor='let x of array;let last = last;'></element> I have been unable to find detaile ...

Error encountered in Angular 17 SSR: Importing module "@angular/ssr" does not have the exported member "REQUEST"

I'm having trouble getting cookies on Angular 17 with SSR. In the past, I was able to use the REQUEST pulled from @nguniversal/express-engine/tokens, but now with @angular/ssr, I can't find where to pull REQUEST from. import { REQUEST } from &apo ...

What is the process for overriding the module declaration for `*.svg` in Next.js?

The recent modification in Next.js (v11.0.x) has introduced new type definitions: For next-env.d.ts (regenerated at every build and not modifiable): /// <reference types="next" /> /// <reference types="next/types/global" /> ...

Angular 2 file upload encountering CORS issue leading to 401 unauthorized error

Encountered a "401 Unauthorized" error in Chrome and Firefox while attempting to upload files using angular 2 CLI to an apache2-server with a PHP backend. Despite trying three different node modules, the issue persists from the OPTIONS-preflight stage, ...

Implementing data binding for arrays of inputs in Angular

Can anyone provide assistance with this code snippet and explain why it is not functioning as expected? I am trying to generate input fields from a string array and bind each input value to its corresponding element in the array. It seems like a common tas ...

The quantity of documents queried does not align with the number of data counts retrieved from Firestore

Facing an issue with calculating the Firestore read count as it keeps increasing rapidly even with only around 15 user documents. The count surges by 100 with each page reload and sometimes increases on its own without any action from me. Could this be due ...

Exporting a Typescript interface from a restricted npm package

I'm working on an npm module using TypeScript that includes several interfaces. In the index.ts file, I export all of the classes and interfaces. I defined the interfaces as "interface dto {a:string;} export default dto". However, when I import the ...