Angular 2窗口全局对象未定义

时间:2017-01-26 23:50:42

标签: 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)并查看它。知道为什么会这样吗?

1 个答案:

答案 0 :(得分:0)

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

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

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