javascript - Angular 2窗口全局对象未定义

标签 javascript angular angular-universal

引用:https://github.com/MarkPieszak/aspnetcore-angular2-universal/blob/master/Client/app/platform-modules/app.browser.module.ts#L51

通用缓存对象正在全局范围内添加,初始状态如下发送到客户端的 html 中:

<script>
  window.UNIVERSAL_CACHE = { } // stuff gets loaded here
</script>

在我的 browser.module.ts 中,我尝试加载初始状态:

// imports

export const UNIVERSAL_KEY = 'UNIVERSAL_CACHE';

@ngModule({
  // bootstrap, imports, providers, etc.
})
export class AppBrowserModule {

    constructor(public cache: CacheService) {
        this.doRehydrate();
    }

    // Universal Cache "hook"
    doRehydrate() {
        let defaultValue = {};
        let serverCache = this._getCacheValue(CacheService.KEY, defaultValue);
        this.cache.rehydrate(serverCache);
    }

    // Universal Cache "hook
    _getCacheValue(key: string, defaultValue: any): any {
        // Get cache that came from the server
        const win: any = window;
        /* I can console.log(win) to see the window object with .UNIVERSAL_CACHE, however if I console.log(win[UNIVERSAL_KEY]) it is undefined. */
        if (win[UNIVERSAL_KEY] && win[UNIVERSAL_KEY][key]) {
            let serverCache = defaultValue;
            try {
                serverCache = JSON.parse(win[UNIVERSAL_KEY][key]);
                if (typeof serverCache !== typeof defaultValue) {
                    console.log('Angular Universal: The type of data from the server is different from the default value type');
                    serverCache = defaultValue;
                }
            } catch (e) {
                console.log('Angular Universal: There was a problem parsing the server data during rehydrate');
                serverCache = defaultValue;
            }
            return serverCache;
        } else {
            console.log('Angular Universal: UNIVERSAL_CACHE is missing');
        }
        return defaultValue;
    }
}

不幸的是,win[UNIVERSAL_KEY] 始终未定义,即使我可以 console.log(win) 并查看它,或者在开发工具中我可以输入 console.log(window.UNIVERSAL_CACHE) 并查看它。知道为什么会发生这种情况吗?

最佳答案

(我没有足够的声誉来发表评论)

问题来自于这个似乎未完成的函数:https://github.com/angular/universal/blob/master/modules/platform-node/node-platform.ts#L418

当我想让消息在生产中消失时,我从生成的 js 文件中手动删除 injectCacheInDocument 函数。

关于javascript - Angular 2窗口全局对象未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41885055/

相关文章:

angular - 使用 Angular 通用开发 :ssr works but build:ssr is not working 设置页面元标记

javascript - AngularJs:排除来自拦截器的一些请求

javascript - Highcharts 中单独着色的数据范围

angular - router.navigate 不导航到定义的路径 html

angular - 继承和依赖注入(inject)

生产环境中的 Angular SSR 'Failed to lookup view'(Ubuntu、Nginx)

javascript - 将函数类型分配给对象的方法

javascript - JS中的射线/矩形相交

angular - NGX-Graph:节点中心的 anchor 路径

angular - 使用 Angular cli 进行服务器端渲染