0

I have this http response from server for my POST request:

{"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. Local storage , 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');
  });

1 Answer 1

1

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. 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
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.