Angular Universal 使用全局浏览器对象,如窗口和本地存储



我相当大的 Angular Universal 应用程序需要使用本地存储和窗口对象。Node.js 不使用这些对象,我收到窗口或未定义本地存储的引用错误。

我知道我可以使用IsPlatformBrowser模块,但我必须在整个应用程序(几百个地方(和将来的使用中添加条件状态。

我可以写一些东西来遍历节点服务器或客户端上的整个项目吗?

我最终为全局对象制作了一个文件。在文件中,我有两个服务,我使用LocalStorageServiceWindowService。我不得不重构相当多的代码,但我找不到更好的解决方案。现在与Angular Universal完美合作。

幸运的是,localStorage是一个简单的浏览器 api,只有 5 个函数和一个属性,所以我可以写出整个东西。但是window有几十个函数和属性,这意味着 Ill 必须在 WindowService 中编写函数,然后再在其他地方使用它。

它相当不优雅,但它有效。

这是我的全局对象文件:

  import { Injectable, OnInit, Inject, PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';
@Injectable({providedIn: 'root'})

export class LocalStorageService {
    constructor(@Inject(PLATFORM_ID) private platformId: Object) {}
    clear() {
        if (isPlatformBrowser(this.platformId)) {
            localStorage.clear();
        }
    }
    setItem(key: string, value: string) {
        if (isPlatformBrowser(this.platformId)) {
            localStorage.setItem(key, value);
        }
    }
    getItem(key: string) {
        if (isPlatformBrowser(this.platformId)) {
           return localStorage.getItem(key);
        }
    }
    removeItem(key: string) {
        if (isPlatformBrowser(this.platformId)) {
            localStorage.removeItem(key);
        }
    }
    key(index: number) {
        if (isPlatformBrowser(this.platformId)) {
            return localStorage.key(index);
        }
    }
    length() {
        if (isPlatformBrowser(this.platformId)) {
            return localStorage.length;
        }
    }

}
export class WindowService {
    constructor(@Inject(PLATFORM_ID) private platformId: Object) {}
    scrollTo(x: number , y: number) {
        if (isPlatformBrowser(this.platformId)) {
         window.scrollTo(x, y);
        }
    }    
    open(url?: string, target?: string, feature?: string, replace?: boolean) {
        if (isPlatformBrowser(this.platformId)) {
        window.open(url, target, feature, replace);
        }
    }
}

最新更新