0

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?

2
  • You should check this nice guide from angular: angular.io/guide/styleguide Commented Jun 7, 2020 at 22:53
  • Hey semicolon ! You mean the global variable in the component will be familiar to other components? Commented Jun 7, 2020 at 23:33

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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));
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.