Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - Whats the best way to store global variables like authentication token so all classes have access to them?

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.

like image 454
AngularM Avatar asked Nov 08 '15 19:11

AngularM


People also ask

What is the best way to declare and access a global variable?

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.

What is token based authentication in angular?

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.

Is there any global variable in angular?

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.


1 Answers

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.

like image 117
Chandermani Avatar answered Oct 14 '22 00:10

Chandermani