简体   繁体   English

如何在angular 2应用程序中从http json响应保存访问令牌?

[英]How to save an access Token from a http json response in angular 2 app?

I have this http response from server for my POST request: 我对服务器的POST请求有以下http响应:

{"token_type":"Bearer","expires_in":35999,"refresh_token":"PvmIMkmgmawTYKrUWUlqRd9pd6itd5JCeHYqKdgoul","access_token":"eyJhbGciOiJSUzI1NiIsImtpZCI6InNpZ25pbmdrZXkiLCJ4NXQiOiJYU09MYWdXd0o5YjlSMjE4LV94Q3BidTdKWnMifQ.eyJzdWIiOiJDb21tYW5kQ2VudHJhbDAxIiwicmVhbG0iOiJtb3Rvcm9sYXNvbHV0aW9ucy5jb20iLCJleHAiOjE0NjU5MzI0NzgsInNjb3BlIjpbIm1zaV91bnNhcGlfZ3JvdXBtZ3QucmVhZCIsIm1zaV91bnNhcGlfZ3JvdXBtZ3Qud3JpdGUiLCJtc2lfdW5zYXBpX3ByZXNlbmNlLndhdGNoIiwibXNpX3Vuc2FwaV9sb2NhdGlvbi53YXRjaCIsIm1zaV91bnNhcGlfbWVzc2FnaW5nIl0sImNsaWVudF9pZCI6IkNvbW1hbmRDZW50cmFsIiwiaXNzIjoiaHR0cHM6Ly9pZG1wc2IuaW13Lm1vdG9yb2xhc29sdXRpb25zLmNvbTo5MDMxIn0.LRS8ifL8VoHNikvbBaqU6rvqAWT_QJh0KUvbUAZNuo77DMr7eredwfdtNNptdYGfbWvpq00g3ydViCT1Xh4IFsY8-8jqvvY3FStlp0eUdzfJ9QnYJFDEBzrh1ccjCX4nxmEeLpaMSwvMbMsi1ByJNcu9OnDvBSJC82c3la9EGInyGOTMI08WncVwq-8zkuTrv9K9n4wRmjvX_FHsY_OUSlpyJk1iiM_MLyCjH8nTgjCkNskGOEgSSDLrEfMHhdewSag4jFY3_O9RIzrkT3lOJ8sm6ykH6IdckqxDlva8_Ej23J7zr5el6uUUxy04iQQjxct6ToFH1u0TVrC4uednTQ"}

What would be the best angular 2 typescript way to save this token, in order to use it for the further get requests to the api. 保存此令牌的最佳角度2打字稿方法是什么,以便将其用于对api的进一步获取请求。 Local storage , cookie ? 本地存储,cookie? how to do it the best way ? 如何做到最好呢? So far I have only a console response: 到目前为止,我只有一个控制台响应:

this.http.post(url, '')
  .map(res => res.json())
  .subscribe(data => {
    console.log(JSON.stringify(data));
    console.log('Completed');
  });

If you get new token data everytime you open up the page, then I'd just store it in a service during runtime. 如果每次打开页面时都获得新的令牌数据,那么我将在运行时将其存储在服务中。

Otherwise, yes - localstorage is a good place to store your information. 否则,是的-localstorage是存储您的信息的好地方。 You could even make yourself a helper service for the storage: 您甚至可以使自己成为存储的帮助服务:

class StorageService {
    static write(key: string, value: any) {
        if (value) {
            value = JSON.stringify(value);
        }
        localStorage.setItem(key, value);
    }

    static read<T>(key: string): T {
        let value: string = localStorage.getItem(key);

        if (value && value != "undefined" && value != "null") {
            return <T>JSON.parse(value);
        }

        return null;
    }
}

So you could use it like: 因此,您可以像这样使用它:

interface IToken {
    token_type: string;
    expires_in: number;
    refresh_token: string;
    access_token: string;
}

[...]

class TokenService {
    private _token: IToken = null;
    private _url: string = "http://...";

    constructor(private _storageService: StorageService,
                private _http: Http) { }

    getToken(callback: (token: IToken) => void) {
        if (this._token) {
            callback(this._token);
        }
        else {
            this._token = this._storageService.read<IToken>('token');
            if (this._token) {
                callback(this._token);
            }
            else {
                this.http.post(this._url, '')
                    .map(res => res.json())
                    .subscribe(token: IToken => {
                        this._storageService.write('token', token);
                        this._token = token;
                        callback(this._token);
                    }
                );
            }
        }
    }
}

In other places where you need the token you can now use it like so: 现在,在其他需要令牌的地方,您可以像下面这样使用它:

this._tokenService.getToken((token: IToken) => {
    // do something here
});

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

相关问题 失败时如何从Angular HTTP Interceptor访问Response主体? - How to access Response body from Angular HTTP Interceptor on failure? Angular 2:如何访问 HTTP 响应正文? - Angular 2: How to access an HTTP response body? 如何在Angular $ http响应中捕获格式错误的JSON? - How to catch malformed JSON in an Angular $http response? Basic Angular-如何将json http响应加载到另一个json对象中 - Basic Angular - How to load json http response into another json object 如何使用角度2中的自定义http刷新访问令牌? - how to refresh the access token using custom http in angular 2? Angular 7:如何从测试用例访问/发送HTTP响应的正文部分 - Angular 7: How to access/send only body part of HTTP Response from test case http:如何从批处理响应中获取 json? - http: how to get json from batch response? 当响应类型是arraybuffer时,如何从HTTP get方法中读取Angular JS中的RAW JSON? - How to read RAW JSON in Angular JS from HTTP get method, when response type is arraybuffer? Angular2:无法返回从Http响应映射的json - Angular2: unable to return a json mapped from an Http response Angular 2 Http get - 从响应中解析JSON对象 - Angular 2 Http get - parsing JSON object from response
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM