How to use localStorage in angular universal?

柔情痞子 提交于 2019-12-07 15:37:58

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/44205591/how-to-use-localstorage-in-angular-universal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!