简体   繁体   English

Angular 2全局变量

[英]Angular 2 global variable

I am trying to set up a global service which can be accessed through out all the components, precisely I wish to store user related information using this service like roles, name etc. and use it later in all components 我正在尝试建立一个可以通过所有组件访问的全局服务,确切地说,我希望使用此服务存储与用户相关的信息,例如角色,姓名等,并稍后在所有组件中使用

I have tried with singleton, but It got clear after browser refresh. 我已经尝试过使用singleton,但是刷新浏览器后它变得很清楚。

How to achieve this any guidance will be appreciated. 如何实现这一目标将不胜感激。

The singleton service is like this: 单例服务是这样的:

    export class Principal{
    private isAuthenticated: boolean = false;
    private roles: Array<String>;
    private fullName: String;
    constructor(){} ;
    // getter and setter

}

You will need to have your service singleton save its state in a browser persistence storage if it is to survive a browser refresh. 为了使服务单例能够在浏览器刷新后幸存下来,就需要将其状态保存在浏览器持久性存储中。 Add some of your singleton code to your original question and I will update this answer with code that saves its state in sessionStorage ; 将一些单例代码添加到原始问题中,然后我将使用将其状态保存在sessionStorage代码来更新此答案;

UPDATE UPDATE

We can use the angular2-localStorage module to accomplish this. 我们可以使用angular2-localStorage模块来完成此任务。

export class Principal{
    @SessionStorage() private isAuthenticated: boolean = false;
    @SessionStorage() private roles: Array<String>;
    @SessionStorage() private fullName: String;
    constructor(){} ;
    // getter and setter
}

PLEASE NOTE 请注意

Do not store any sensitive values here. 不要在此处存储任何敏感值。 Your backend API should NOT trust any of these values as the end user can easily change these. 您的后端API不应信任任何这些值,因为最终用户可以轻松更改这些值。

With idomatic typescript you should prefer get and set accessors rather than getter and setter methods. 使用idomatic打字稿,您应该更喜欢getset访问器,而不是getter和setter方法。

This corresponding service provider must be specified when bootstrapping your application or within the providers attribute of the main component. 在引导应用程序时或在主要组件的providers属性内,必须指定此相应的服务提供者。

bootstrap(AppComponent, [ GlobalService ]);

or 要么

@Component({
  (...)
  providers: [ GlobalService ]
})
export class AppComponent {
}

This way all your components will share the same instance of the service. 这样,您的所有组件将共享服务的同一实例。

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

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