Angular Universal使用全局浏览器对象,如window和localstorage

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

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

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

有什么我可以写的只是在节点服务器或客户端上的整个项目?

node.js angular angular-universal
1个回答
0
投票

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

幸运的是localStorage是一个简单的浏览器api,只有5个函数和一个属性,所以我可以写出整个事情。然而window有许多功能和属性,这意味着我必须在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);
        }
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.