如何在角度通用中使用localStorage?

Pra*_*ana 5 local-storage angular-local-storage angular-universal angular

我正在使用 @angular v4.0.3 和 webpack 2.2.0。

使用Auler post工作正常,但当我包含 localStorage 时它停止工作。有什么方法可以使它在 angular Universal 中工作或用于 localStorage 的任何模块

Est*_*ask 7

一个好方法是制作localStorage一个可注入对象并为其提供不同的实现。

一个反映StorageAPI的抽象类可以作为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;
}
Run Code Online (Sandbox Code Playgroud)

然后对于浏览器应用程序模块它是

export function localStorageFactory() {
  return localStorage;
}
...
{ provide: LocalStorage, useFactory: localStorageFactory }
Run Code Online (Sandbox Code Playgroud)

对于服务器应用程序模块localStorage可以替换为一些实现,例如node-storage-shim内存存储:

{ provide: LocalStorage, useClass: StorageShim }
Run Code Online (Sandbox Code Playgroud)

使用 DI 而不是全局持久存储也使测试更容易。