Something similar to $ rootScope

1

I have been looking for a way to have global variables for the whole application, something similar to the rootScope of angular 1 I searched the angular api 4 and I have not found an answer if someone went through this problem I appreciate your help

    
asked by Ricardo 16.11.2017 в 23:01
source

2 answers

0

You could use the concept of LocalStorage, which is provided by browsers and allows you to store data of any kind and obtain them anywhere in your application. You can research a little more here .

Here below is a simple example, I hope it will be useful.

To save an object: It is like a "Map" a key is associated, in this case 'name' and a value.

localStorage.setItem('nombre', data);

To take the data: The key is used.

localStorage.getItem('nombre');

To remove the localStorage object: The key is used.

localStorage.removeItem('nombre');
    
answered by 18.12.2017 в 12:57
0

To keep 'global' variables in memory:

  • If they are going to be constant use the file environment.ts .

  • If they are not going to be, use a service and import it into the module as you need, in case of a single module application in AppModule in case of an application with shell Architecture in the SharedModule .

To maintain 'global' variables in the client's browser:

  • localStorage will keep it for a while, but you do not have access to this data from the server, in case you use SSR and also you must constantly be serializing with% % co and deserializing data for use with JSON.stringify .

  • cookies will keep it as long as you indicate, you will have access to these cookies from the server and the serialization and deserialization is transparent with the recommended library universal-cookie .

  

Even so, all this, you will always have to import and / or inject to be able to use these 'global variables'.

The best option, based on experience, is to create the shared service and cookies.

    
answered by 27.12.2017 в 00:00