Angular 2中的用户特定变量

时间:2017-07-28 08:23:08

标签: angular web-services typescript

我是Angular的新手,我一直在阅读,但仍然无法找到一种正确的方法来处理用户特定的变量(让我们说用户名)。也就是说,这些变量可以被任何组件访问和编辑(我试图避免全局变量,因为我认为它们不适合这个具体情况)

1 个答案:

答案 0 :(得分:0)

您可以使用浏览器本地存储来存储特定于用户的数据  username / Userprofile / authtoken等

let userProfile = {username: 'abc', ...};
localStorage.setItem('UserLocalProfile', userProfile);

您也可以将其删除

localStorage.removeItem('UserLocalProfile');

你可能会编写服务并注入Angular组件,以便更好地满足你的需求。

这里是开始的例子..

import { Injectable } from '@angular/core';

@Injectable()
export class TokenService {
    constructor() { }

    private storageName: string = "UserLocalStorage";

    setToken(token: string) {
        localStorage.setItem(this.storageName, token);
    }

    getToken() {
        let token = localStorage.getItem(this.storageName);
        return token;
    }

    clearToken() {
        localStorage.removeItem(this.storageName);
    }
}