1

I have some data from a function in my app.component that I would like to store and use in other components. How can I achieve this?

Here is the function:

private async setupLocalUser(): Promise<boolean> {
try {
  this.token = await jwtDecode(this.oauthService.getAccessToken());
  //add user
  this.userId = await this.userService.AddUser(this.token.email);
  //add user session
  this.userSessionId = await this.userSessionService.AddUserSession(this.token.email);
  return true;
}
catch (Error) {
  this.errorMessage = Error;
  return false;
}

this.userSessionId is what I'd like to store for use as a parameter in different functions that are in other components. How can I achieve this?

JCA
  • 197
  • 2
  • 2
  • 16
  • This is basically the same question you asked [here](https://stackoverflow.com/questions/61918572/how-to-store-a-string-for-later-use-in-angular-from-a-post-method-api-call). Did you review the documentation on [component interaction](https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service) and tried creating a service to store this value? You can use services to store and share data across your application. – Alexander Staroselsky May 20 '20 at 22:37
  • Have a look at the following answer to get an idea: https://stackoverflow.com/a/46049546/1791913 – FAISAL May 20 '20 at 22:49

2 Answers2

-1

Take a look at this post, I'm sure it'll be useful for your problem. As they say there, you could use a service or sessionStorage (more info here) to store the data so it can be accessed across the application.

I hope this helps you!

mhSangar
  • 457
  • 3
  • 12
-1

There is number of ways by using you can store/transfer data across the components. It totally depends on your situation/requirement. For example, you can use

  • Service's
  • web storage (Localstorage/ SessionStorage/ Cookies etc)
  • Global Variables
  • Variables as behaviour subject.

But I would suggest if the value is confidential you should store in a Global variable or using services. By doing so it's a bit hard for anyone to fetch data from the production build.

Let me know if you still have any query.

Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215