问题
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