Home > Mobile >  Getting user Id in Angular?
Getting user Id in Angular?

Time:07-23

I want to get the userId of the current user signed in and post it into another method colled AddExperience that contains that userId as a parameter ( foreign Key). The UserId is stored in LocalStorage after loging in !

this is the action from the service :

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

And these are the localeStorage values :

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

What should I do in the AddExperience TypeScript file to add the Experience with the current User?

CodePudding user response:

The way retrieve something from the localStorage in Angular its first import

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

Then in constructor I declare a protected variable from wich Angular automatic creates a local variable

constructor(protected storage: StorageMap) { }

And then you can call the method inside this storage local variable like this

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`);
        }
      })
    );
  }

Then you could use it in your particular case like this

    public userIdObtainedFromLocalStorage: string = '';

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

})

CodePudding user response:

Can I do sthg like this ?

cl = localStorage.getItem('ID'); AddExperience(cl : any){ return this.http.post(this.rootUrl '/AddExperience' cl, {responseType: 'json'}); }

  • Related