简体   繁体   English

如何在Angular2中存储全局变量?

[英]How to store global variable in Angular2?

How to store global variable in Angular2, same with session of PHP? 如何将全局变量存储在Angular2中,与PHP会话相同?

instead use: 改为使用:

localStorage.setItem();

You could use a shared service for this. 您可以为此使用共享服务。 To have a unique instance of the service for the whole application, simply define it within the bootstrap function: 要为整个应用程序提供唯一的服务实例,只需在bootstrap函数中定义它:

bootstrap(AppComponent, [ SharedService ]);

This way, you will be able to set your global variable in it. 这样,您将可以在其中设置全局变量。

export class SomeComponent {
  constructor(private service:SharedService) {
    this.service.someProperty = 'some value';
  }
}

Every elements (components, services) that inject this service will have access to this service. 注入该服务的每个元素(组件,服务)都可以访问该服务。

If you want to be notifed when this field is updated, you could use an observable property as described below: 如果要在更新此字段时被通知,可以使用如下所述的observable属性:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM