Home > Software design >  How can i save data of the current logged in user in an array in Angular
How can i save data of the current logged in user in an array in Angular

Time:08-02

In the component Template, we can use "*ngIf="user$ | async as user"", to access all the data stored in the user... Please i need to access all of those data in the component.ts file and save them to an array, variable , I need to attach them to a js config file going to an API.... Is it possible to use the async pipe to access them in the ts file?

 var gameConfig = {
      gameServer: "${server}",
      gameCode: "${gameCode}",
      apiKey: "${api}",
      username: "${username}",
      sessionKey: "${sessionID}",
      languageCode: "${language}",
      currencyCode: "${CurrencyCode}",

I have all those stored parameters stored in the current user profile and i can call the current logged in user as user$ = this.usersService.currentUserProfile$;.... just want a way to tap into the user$ and access all of those data.

CodePudding user response:

You already answered the question. You have to tap into the values of the user$ in the TypeScript file. There is an RxJS operator just named tap.

tap operator is:

Used to perform side-effects for notifications from the source observable

Since user$ is an observable you can subscribe to it (or use the tap) and map the values to your config. To use tap you have to wrap it inside a pipe(). You will need to do something like this in your ngOnInit(){}

ngOnInit(){
 this.user$.pipe(tap((response)=> console.log(response)))
}

PS: next time please provide more context to help people help you. Also do not forget to unsubscribe from this observable to avoid memory leak

CodePudding user response:

You have got the Observable in your .ts file; that is user$, where you can subscribe to, and get the result like this

user$.subscribe((res) => {
  console.log(res);
)};

Whereas async is a pipe you use in your .html

Note: If you are going to subscribe anyway to this Observable, then there's no need to use the async pipe in your .html, because you would probably want to assign the response of your subscription to a local instance user for example, sample code for this use case would be like this:

user$.subscribe((res) => {
  console.log(res);
  this.user = res;
)};

Tip: Always use ngOnDestroy() life cycle hook to unsubscribe() your Observable in your .ts file.

  • Related