Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save user object in Session Storage

I am using Angular 2 and Typescript and wanted to save the user object like a global variable so it hasn't to be retrieved multiple times. I found the session storage and now save the user object there.

Do you think it is good practice to store it there or is the data too sensitve? If so, what other kind of cache could I use?

Here is the code I use right now:

user.service.ts:

getProfile() {
    let cached: any;
    if (cached = sessionStorage.getItem(this._baseUrl)) {
        return Observable.of(JSON.parse(cached));
    } else {
        return this.http.get(this._baseUrl).map((response: Response) => {
            sessionStorage.setItem(this._baseUrl, response.text());
            return response.json();
        });
    }
}

The getProfile() is called in the app.component when ngOnInit(). The user object is also needed in other components of the application.

like image 700
sanyooh Avatar asked Jan 10 '17 08:01

sanyooh


People also ask

Can we store window object in session storage?

You can't persist a window object in local storage. You can only store data in the form of strings in local storage, and there is no way to turn the window object into a string so that you can recreate the same window object.


2 Answers

Its ok to have secure/sensitive data in session storage.

As session storage only available for current table and domain...

If user check same session storage data in another window tab then it will not be there....so its secure storage....

If want to know more, please have look on sessionStorage

like image 192
Pankaj Badukale Avatar answered Sep 28 '22 10:09

Pankaj Badukale


You could either use sessionStorage or use a service.

Your interface:

export interface ISession {
    session:Object
}

Your actual service class:

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

    @Injectable()
    export class SessionService implements ISession {    
        private _session: session

        constructor(){

        }

        set session(value){
            this._session = value;
        }

        get session(){
            return this._session
        }
   }

Now you can inject this SessionService class in other class constructors and use it.

like image 45
Thalaivar Avatar answered Sep 28 '22 10:09

Thalaivar