问题描述
我正在使用@angular v4.0.3和webpack 2.2.0.
I am using @angular v4.0.3 and webpack 2.2.0.
使用 Auler 发布,但由于我包含了localStorage,因此它停止工作.有什么办法可以使它正常工作或在angular Universal中为localStorage使用任何模块
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
推荐答案
一个好方法是使localStorage
成为可注入对象并为其提供不同的实现.
A good way is to make localStorage
an injectable and provide different implementations for it.
反映的抽象类Storage
API 可以用作令牌:
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 }
对于服务器应用模块localStorage
可以替换为某些实现,例如 node-storage-shim
用于内存中存储:
And for server app module localStorage
can be replaced with some implementation, like node-storage-shim
for in-memory storage:
{ provide: LocalStorage, useClass: StorageShim }
使用DI代替全局持久性存储也使测试更加容易.
Using DI instead of global persistent storage also makes testing easier.
这篇关于如何在Angle Universal中使用localStorage?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!