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?
-
You should check this nice guide from angular: angular.io/guide/styleguideElias Soares– Elias Soares2020-06-07 22:53:03 +00:00Commented Jun 7, 2020 at 22:53
-
Hey semicolon ! You mean the global variable in the component will be familiar to other components?Pluto– Pluto2020-06-07 23:33:36 +00:00Commented Jun 7, 2020 at 23:33
Add a comment
|
2 Answers
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));
}