I am using @angular v4.0.3 and webpack 2.2.0.
It was working fine using Auler post but as I included localStorage it stopped working. Is there any way to make it work or any module for localStorage in angular universal
A good way is to make localStorage
an injectable and provide different implementations for it.
An abstract class that reflects Storage
API can be used as a token:
export abstract class LocalStorage {
readonly length: number;
abstract clear(): void;
abstract getItem(key: string): string | null;
abstract key(index: number): string | null;
abstract removeItem(key: string): void;
abstract setItem(key: string, data: string): void;
[key: string]: any;
[index: number]: string;
}
Then for browser app module it is
export function localStorageFactory() {
return localStorage;
}
...
{ provide: LocalStorage, useFactory: localStorageFactory }
And for server app module localStorage
can be replaced with some implementation, like node-storage-shim
for in-memory storage:
{ provide: LocalStorage, useClass: StorageShim }
Using DI instead of global persistent storage also makes testing easier.
This happens because using Angular Universal for Server Side Rendering, the Angular app runs in both the Nodejs server and the client browser. At this point, the server app does not have a reference to the localStorage object, because it is only available on the client-side.
There's an article I wrote about this with the solution implemented: How to use localStorage on Angular 9 Universal (SSR)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With