Sharing sessionStorage between tabs in Angular 2 then immediately using it?

Erik Kránicz picture Erik Kránicz · Feb 15, 2017 · Viewed 7.1k times · Source

What I already know:

What I use:

  • Angular 2 (v2.4.4) with TypeScript on Angular CLI base

The actual problem:

The script (which shares the sessionStorage between tabs) runs within Angular before HTTP requests, but when the page creates a HTTP request, it uses a session id (which is sent to the server in order to identify the session) and the session id should be taken from sessionStorage, but it is not there yet.

When I open the browser's debugger console (on the new tab), the sessionStorage is there. And because of this when I reload this new tab everything works just fine. But the problem is that the sessionStorage was set after HTTP request already tried to use.

The above linked solution truly runs before HTTP calls, but the event calls happen after HTTP calls. I think about especial sessionStorage_transfer from the above linked code:

window.addEventListener("storage", sessionStorage_transfer, false);

I store the session id like this:

get sid(): string {
    return sessionStorage.getItem('user.sid') || '';
}
set sid(value: string) {
    sessionStorage.setItem('user.sid', value);
}

So eventually sid receives value but just after the HTTP call already tried to use it despite the fact that the script (which shares sessionStorage) started to run before any HTTP call.

(If there is no solution then I will use session cookie for sid alone but I hope someone knows a solution for this. Perhaps a Promise, Observable, Subject, anything?)

Thank you for your solutions! :-)

Answer

Chaitanya Chauhan picture Chaitanya Chauhan · Nov 20, 2017

keep the code from here mentioned in correct answer in your index.html of your angular web-app. It worked for me.