Angular 2 question only:
Whats the best way to store global variables like authentication token or base url (environment settings) so that all classes can have access to them without loosing them on refresh?
So when I login I will give the user a auth token and normally store it in the $rootscope for angular 1.x.
The clean, reliable way to declare and define global variables is to use a header file to contain an extern declaration of the variable. The header is included by the one source file that defines the variable and by all the source files that reference the variable.
JWT-based User Sessions The key thing about JWTs is that in order to confirm if they are valid, we only need to inspect the token itself and validate the signature, without having to contact a separate server for that, or keeping the tokens in memory or in the database between requests.
We always need to declare global variable file for our angular 10 application because we can set some global variable there like site title, api url etc so you can easily access any where in our application easily. So, in this example, we will create GlobalConstants file for adding global variables in our application.
Well to create really global scope data you should register your class\object\value during the app bootstrapping as dependency parameter to the bootstrap function
bootstrap(MyApp,[MyGlobalService]);
This will register your service MyGlobalService
(infact it can be a object or factory function or your own provider) at the root level. This dependency now can be injected into any component.
Unlike Angular1 there are multiple Injectors available for an Angular2 app, with one-to-one mapping between components and injectors. Each component has its own injector.
The Angular developer guide has some good example of such registrations. See the guide on Dependency Injection.
The other option has already been highlighted by @Yaniv.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With