Save user object in Session Storage
Asked Answered
S

2

12

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.

Saphead answered 10/1, 2017 at 8:21 Comment(3)
Why don't you use service?Dale
I do use a service. I can add my code.Saphead
You could use local storage which as session storage is only available on the current tab but persists after closing (you'll have to explicitly remove it). More details on differences between the two here #5523640Ryder
B
12

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

Branchia answered 10/1, 2017 at 8:42 Comment(0)
S
9

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.

Sandal answered 10/1, 2017 at 9:23 Comment(5)
I am going to try it out!Saphead
this will show undefined until i don't use localStorage or sessionStorage, is it right?Hydric
This is a service so technically if you don't set anything, it will be undefined... unless a default value is set.Sandal
but what a hard refresh on the browser tab will do with that data??? You could explain the use of localStorage tooBauman
If user types the url to another route, (not through clicking a routerLink), I think this service will be initiated again, meaning the previous set values will lost.Dicot

© 2022 - 2024 — McMap. All rights reserved.