How to retrieve user ID using Angular?

I need to extract the userId of the current signed-in user and pass it as a parameter (foreign Key) to another method called AddExperience. The userId is stored in LocalStorage after logging in!

Here is the action from the service:

AddExperience(UserId: any) { return this.http.post(this.rootUrl + '/AddExperience'+ UserId, {responseType: 'json'}); }

These are the values stored in localStorage:

token-exper: 2122-07-23T01:40:15Z
UserRole: User
ID: 2aa0f755-cf7d-4c62-bfe8-1de35ee01b09

What steps should I take in the AddExperience TypeScript file to associate the Experience with the current User?

Answer №1

To access information stored in the localStorage using Angular, start by importing the necessary module

import { StorageMap } from '@ngx-pwa/local-storage';

In the constructor, declare a protected variable that Angular will convert into a local variable

constructor(protected storage: StorageMap) { }

You can then utilize the methods within this local storage variable as shown below

public get<D, M>(key: string) {
    return this.storage.get(key).pipe(
      map((item?: any) => {
        if (item) {
          return new StorageItem(item?.data, item?.meta, item?.meta?._creationTimestamp);
        } else {
          return new StorageItemError(`Data of ${key} was not found in Storage`);
        }
      })
    );
  }

Finally, you can implement it in your specific scenario like this

    public userIdObtainedFromLocalStorage: string = '';

    this.get('ID').subscribe((userId: string) => {
    this.userIdObtainedFromLocalStorage = userId;

})

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

What is the process for accessing and updating values within nested form fields in angular2?

I have been working on an Angular 2 application that utilizes Angular reactive forms. I need to retrieve the value of the innermost element and then update that value accordingly. form : FormGroup; constructor(private formBuilder: FormBuilder) { this. ...

"Exploring the dynamic capabilities of Angular 15 with Ngrx store

I have been struggling for a while now, trying various approaches, but I just can't seem to find a solution to this issue. constructor(protected subjectService: SubjectsService, protected userService: UsersService, protec ...

Using the oidc-client library in Angular to create a customized isLoggedIn() function within *ngIf implementation

Objective: I'm trying to toggle the visibility of a Login and Logout button in an Angular application using IdentityServer4 and OIDC client. Issue: The isLoggedIn function in my code returns undefined before it returns true, causing the *ngIf directi ...

I am experiencing difficulty in retrieving the content-disposition from the client

I am attempting to retrieve a .xlsx file that is generated on the backend using Spring Boot. I am able to retrieve headers on the frontend, which include the content-disposition as shown below. However, I am unable to access the content disposition in the ...

Error: The function gtag within the window object is not recognized

I've been struggling with GTM lately. I integrated it into my website to handle traffic and trigger events, but for the past 2 days, I've been encountering this error: Error from the trackerPageView => TypeError: window.gtag is not a function ...

TS7016: No declaration file was found for the module named 'rxjs'

I recently updated my Angular App dependencies and successfully installed them. However, I am now facing an issue with 'rxjs'. The IDE returned the following error: TS7016: Could not find a declaration file for module 'rxjs'.'C:/ ...

How do EventEmitter<undefined> and EventEmitter<void> differ from each other?

At times, there may be a situation where we need to omit the generic variable. For example: @Component( ... ) class MyComponent { @Output() public cancel = new EventEmitter<undefined>(); private myFoo() { this.cancel.emit(); // no value ...

Issue with Service Fabric - Unable to run Angular project on local Windows machine: EPERM error preventing operation

For testing purposes, I have locally installed Service Fabric. As a preliminary test, I created a basic C# app with an Angular front end without making any changes to it. When I try to run the app, I encounter the following error: An unhandled exception oc ...

Transmitting information from a modal component to its parent component in Angular using MDB

I encountered an issue with my CRUD application where uploaded files do not immediately appear on the page until I refresh it. The same problem occurs when trying to delete a file. For deleting, I was able to fix it by subscribing to the onClose event on ...

How can you obtain the key that comes after or before an existing key in a sorted TypeScript string enum?

Given the key STEPS.GENDER and the string enum below export enum STEPS { NAME = "name", GENDER = "gender", BIRTHDAY = "birthday", SUCCESS = "success" } Is there a way to programmatically determine the next o ...

Reorganizing Execution Order in AfterViewInit with Subscriptions in Angular 10

In my component, I am using the ngAfterViewInit lifecycle hook to handle certain tasks: ngAfterViewInit() { this.sort.sortChange.subscribe(() => this.paginator.pageIndex = 0); this.subscription = this.dataService.dataChanged .subscribe( ...

Guidelines for releasing Node.js microservice client as a stand-alone package within the repository

For my current web application project, I have chosen to implement the client <-> api <-> [microservices] pattern. To challenge myself, I am developing my microservices in Clean Architecture with node.js using Typescript. Although I have alrea ...

Steps for configuring Types in Graphql Codegen

I have successfully implemented a Vue 3 component that utilizes Urql to query a Hasura graphql endpoint. The query is functioning properly, but I am now focused on enhancing the type safety of the component. My approach involves using graphql Codegen to g ...

"Connecting multiple URLs to the same router link: A step-by-step guide

I am currently working on a small test project in Angular and I aim to incorporate a side navigation using Angular router outlet. My goal is to have two links: <a class="nav-link text-white" [routerLink]='["/link/to/one"]' routerLinkActive="a ...

What is the mechanism behind lazy module loading in typescript?

Exploring the concept of lazy loading in typescript, the author provides an example in this section of their book. They demonstrate it using the following piece of code: import bar = require('bar'); export function loadBar() { ...

Utilizing the Cerialize Library in Angular 2 to bind the properties of an object item to a class

Summary of JSON data: { "courses_purchased_count": 0, "featured_lesson": { "lesson": { "id": 290, "name": "Christmas Test #290", "course": { "id": 43, "name": "Christmas Test", "description": ...

How to identify the type of a union type in Typescript

I am curious about the type c used in the printTypeOf function. Check out my code below: type Email ={ email:string, } type Phone ={ phone:string, } type ContactInfo = Email | Phone; function printTypeOf(c: ContactInfo) { console.log(typeof c ...

Utilizing Angular 2's Routerlink with *ngIf and Parameters

Currently, I am facing an issue with a routerlink that includes a parameter: http://localhost:4200/item/1 I am trying to figure out how to implement an *ngIf statement with a parameter.... Here is what I have attempted so far: <div *ngIf="router.url ...

Exploring Angular: how RxJS enhances the power of making http requests

I'm currently working on a project using Angular 14.1, and I'm in need of creating a service that can retrieve data from multiple endpoints. The service needs to quickly fetch the required information as it will be used by a component. Here is m ...

Angular: define an object with multiple nested levels using variables for keys and values

I am working on a React form where I have an array of objects for each field component. My goal is to compile these objects into one object containing all the form values. interface FormProps { name: string; subName?: string; value: undefined | strin ...