Angular 2全局变量 [英] Angular 2 global variable

查看:110
本文介绍了Angular 2全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试建立一个可以通过所有组件访问的全局服务,确切地说,我希望使用此服务存储与用户有关的信息,例如角色,姓名等,并稍后在所有组件中使用

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

我已经尝试过使用singleton,但是刷新浏览器后它变得很清楚.

I have tried with singleton, but It got clear after browser refresh.

如何实现这一目标,将不胜感激.

How to achieve this any guidance will be appreciated.

单例服务是这样的:

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

}

推荐答案

如果要使服务单例能够在浏览器刷新后幸存下来,就需要将其状态保存在浏览器持久性存储中.将一些单例代码添加到原始问题中,然后我将使用将其状态保存在sessionStorage中的代码来更新此答案;

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;

更新

我们可以使用 angular2-localStorage 模块来完成此操作.

We can use the angular2-localStorage module to accomplish this.

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

请注意

请勿在此处存储任何敏感值.您的后端API不应信任任何这些值,因为最终用户可以轻松更改这些值.

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.

使用idomatic打字稿,您应该更喜欢getset访问器,而不是getter和setter方法.

With idomatic typescript you should prefer get and set accessors rather than getter and setter methods.

这篇关于Angular 2全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆