如何仅在浏览器上访问本地存储angular ssr

问题描述 投票:0回答:1

我正在尝试使用以下代码将浏览器存储注入我的角度应用程序:

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

如何定义存储,以便定义存储并运行我的应用程序?

angular nestjs server-side-rendering angular-universal universal
1个回答
0
投票

您可以尝试这两个选项之一

选项1

修改您的工厂以接受平台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]
});

选项2

修改您当前的服务实现以注入平台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;
  }
© www.soinside.com 2019 - 2024. All rights reserved.