1

I have moved my application from Angular 6 to Angular Universal and since doing this I have noticed this error in the console:

sessionStorage is not defined

It is moaning about this service:

export class SessionService {
  constructor(
    private key: string
  ) { 
  }

  save(json: any) {
    sessionStorage.setItem(this.key, JSON.stringify(json));
  }

  get() {
    return JSON.parse(sessionStorage.getItem(this.key));
  }

  clear() {
    sessionStorage.clear();
  }
}

I have seen that you can do something like:

 if (!isPlatformBrowser(this.platformId)) return;

but this service is actually extended like this:

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

import { SessionService } from './session.service';

@Injectable({
  providedIn: 'root'
})
export class QuestionSessionService extends SessionService {
  constructor() {
    super(
      'questions'
    );
  }
}

So I can't add @Inject(PLATFORM_ID) private platformId: Object to the constructor.

Can someone help me out with this issue?

r3plica
  • 13,017
  • 23
  • 128
  • 290
  • https://stackoverflow.com/questions/43812124/angular-isplatformbrowser-checking-against-platform-id-doesnt-prevent-server-si – rijin Dec 11 '18 at 15:18
  • did you try to inject `PLATFORM_ID` in the parent service? – Guerric P Dec 11 '18 at 15:19
  • I don't think I can do that, because it would make all other services (that extend it) require an extra constructor parameter – r3plica Dec 11 '18 at 15:25

1 Answers1

0

inside your sessionService add check whether you are on the browser side or not by

if (!isPlatformBrowser(this.platformId));

if you are on the browser-side do what you are now doing. but if you are on the SR side use memoryStorage or any other non operable dummy registration which would not cause this error.

hope it helps.

Derviş Kayımbaşıoğlu
  • 28,492
  • 4
  • 50
  • 72
  • I can't do that, I have already stated that because the service is injected I can't add anything to the constructor because it messes with all the services that extend the base class...... – r3plica Dec 11 '18 at 15:41
  • can't you consider altering sessionStorage on any other layer only for SR? so it wont be null on SR side? – Derviş Kayımbaşıoğlu Dec 11 '18 at 15:45