Reputation: 265
How to create a global variable in Angular? I created a variable in service, in component login I enter a value after which I access a variable found in service through another component and the value of the variable in service is reset. What do I need to add or change?
Upvotes: 0
Views: 68
Reputation: 2614
You can also use the simple localStorage
api if you want also keep the data between page reloads. Depends of your goals one or other approach could be better.
Also usgin a service, with a very simple code like this (inside a service of course):
saveItemOnStorage(item, key) {
localStorage.setItem(key, JSON.stringify(item));
}
removeItemFromStorage(key){
localStorage.removeItem(key);
}
getItemFromStorage(key) {
return JSON.parse(localStorage.getItem(key));
}
Upvotes: 0
Reputation: 1815
you need to provide the service in the highest level module only, this way it will work as a singleton (only one instance shared between components, so the values won't reset),
but you are probably providing it in each of these components so each one is getting a new instance of it.
Upvotes: 1