This is a follow-up question to an earlier question I posted.
My question there was about strange log output I was getting when calling a method on a service. The console.log
output was not printing the data that the service clearly defined. The culprit as it turns out was that when calling the service method, the context that is used is the context of the component making the call.
So my question is: What is the proper way to store variables across multiple components in Angular 2+?
For example, say I wanted to keep a variable isLoggedIn
. Where do I keep this variable? I cannot keep it in a service because when components call that service (i.e. authService.getLoggedInStatus()
) they will not neceesarily get the isLoggedIn
value of the service, but rather, potentially, of an identically named variable in the component.
So how do you keep track of shared variables in Angular?
If you would like to keep a global variable
isLoggedIn
accessable anywhere in the application, placing it in a@Injectable service
as a singleton service is completely valid. In order to make sure it is singleton service you should only declare it in app.modules e.gIf you also add it in the components via so:
You initialize a new Service instance, and your intended global
isLoggedIn
would have it's own instance in this component.Hope this give you some sense of how to store global variables using
@Injectable()
in angular.More information on Dependency Injection here.