Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use localStorage in angular universal?

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

like image 876
Praveen Rana Avatar asked May 26 '17 15:05

Praveen Rana


2 Answers

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.

like image 187
Estus Flask Avatar answered Oct 16 '22 23:10

Estus Flask


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)

like image 2
Santi Barbat Avatar answered Oct 16 '22 23:10

Santi Barbat