[英]Creating an Angular Global Variable
How to create a global variable in Angular?如何在 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 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),您只需要在最高级别的模块中提供服务,这样它将作为 singleton 工作(组件之间仅共享一个实例,因此值不会重置),
but you are probably providing it in each of these components so each one is getting a new instance of it.但是您可能在这些组件中的每一个中都提供了它,因此每个组件都获得了它的一个新实例。
You can also use the simple localStorage
api if you want also keep the data between page reloads.如果您还想在页面重新加载之间保留数据,也可以使用简单的
localStorage
api 。 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));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.