我正在尝试使用以下代码将浏览器存储注入我的角度应用程序:
import {Inject, Injectable, InjectionToken} from '@angular/core';
export const BROWSER_STORAGE = new InjectionToken<Storage>('Browser Storage', {
providedIn: 'root',
factory: () => localStorage
});
@Injectable({
providedIn: 'root'
})
export class BrowserStorageService {
constructor(@Inject(BROWSER_STORAGE) public storage: Storage) {
}
get(key: string) {
return this.storage.getItem(key);
}
set(key: string, value: string) {
this.storage.setItem(key, value);
}
remove(key: string) {
this.storage.removeItem(key);
}
clear() {
this.storage.clear();
}
}
但是它会在服务器上引发错误,并且应用程序无法运行
ERROR ReferenceError: localStorage is not defined
如何定义存储,以便定义存储并运行我的应用程序?
您可以尝试这两个选项之一
修改您的工厂以接受平台ID
declare let localStorage: any;
export function localStorageFactory(platformId: Object)
{
return isPlatformBrowser(platformId)? localStorage: null; //Don't use null, use a dummy implementation that does not rely on localStorage
}
export const BROWSER_STORAGE = new InjectionToken<Storage>('Browser Storage', {
providedIn: 'root',
factory: () => localStorageFactory,
deps: [PLATFORM_ID]
});
修改您当前的服务实现以注入平台ID令牌
@Injectable({
providedIn: 'root'
})
export class BrowserStorageService {
private readonly isBrowser;
constructor(@Inject(BROWSER_STORAGE) public storage: Storage, @Inject(PLATFORM_ID) private platformId: Object) {
this.isBrowser = isPlatformBrowser(platformId);
}
get(key: string) {
//check if browser or not
return this.isBrowser? this.storage.getItem(key) : null;
}