首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Angular 2窗口全局对象未定义

Angular 2窗口全局对象未定义
EN

Stack Overflow用户
提问于 2017-01-27 07:50:42
回答 1查看 778关注 0票数 1

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

通用缓存对象在全局添加,初始状态类似于发送到客户端的html:

代码语言:javascript
复制
<script>
  window.UNIVERSAL_CACHE = { } // stuff gets loaded here
</script>

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

代码语言:javascript
复制
// 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)并看到它。你知道为什么会发生这种情况吗?

EN

回答 1

Stack Overflow用户

发布于 2017-02-11 18:53:52

(我没有足够的名气来评论)

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

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41885055

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档