Skip to content Skip to sidebar Skip to footer

How To Store A String For Later Use In Angular From A Post Method Api Call?

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 ad

Solution 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 classAppDataStore{
   private _sessionId: string;
   get sessionId() {
       returnthis._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 = awaitthis.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;

Post a Comment for "How To Store A String For Later Use In Angular From A Post Method Api Call?"