Angular 通用 npm 运行 serve:ssr returns "document is not defined"

Angular Universal npm run serve:ssr returns "document is not defined"

我最近为 Angular 8 实现了 Angular 通用。但是 运行 npm run serve:ssr returns 以下内容:

ReferenceError: document is not defined
    at new CssKeyframesDriver (/Users/timfuhrmann/Documents/Entwicklung/norebro/node_modules/@angular/animations/bundles/animations-browser.umd.js:4379:26)
    at instantiateSupportedAnimationDriver (/Users/timfuhrmann/Documents/Entwicklung/norebro/node_modules/@angular/platform-browser/bundles/platform-browser-animations.umd.js:412:88)
    at _callFactory (/Users/timfuhrmann/Documents/Entwicklung/norebro/node_modules/@angular/core/bundles/core.umd.js:21002:24)
    at _createProviderInstance (/Users/timfuhrmann/Documents/Entwicklung/norebro/node_modules/@angular/core/bundles/core.umd.js:20960:30)
    at resolveNgModuleDep (/Users/timfuhrmann/Documents/Entwicklung/norebro/node_modules/@angular/core/bundles/core.umd.js:20921:25)
    at _createClass (/Users/timfuhrmann/Documents/Entwicklung/norebro/node_modules/@angular/core/bundles/core.umd.js:20989:72)
    at _createProviderInstance (/Users/timfuhrmann/Documents/Entwicklung/norebro/node_modules/@angular/core/bundles/core.umd.js:20957:30)
    at resolveNgModuleDep (/Users/timfuhrmann/Documents/Entwicklung/norebro/node_modules/@angular/core/bundles/core.umd.js:20921:25)
    at _callFactory (/Users/timfuhrmann/Documents/Entwicklung/norebro/node_modules/@angular/core/bundles/core.umd.js:21008:71)
    at _createProviderInstance (/Users/timfuhrmann/Documents/Entwicklung/norebro/node_modules/@angular/core/bundles/core.umd.js:20960:30)

有人知道那是什么意思吗?

客户端 code/keywords 如 DocumentWindowlocalstorage 等将不会出现,而 运行 在您的 SSR/Universal 模式下angular 应用程序作为您的第一个页面将呈现在服务器上。

window, document, localstorage, navigator, and other browser types - do not exist on the server - so using them, or any library that uses them (jQuery for example) will not work in the SSR mode.

因此,如果您的代码中存在任何此类代码,那么您需要将客户端代码包装在 platformBrowser 中,就像这样 -

import { ..., PLATFORM_ID, ... } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';


constructor(
    @Inject(PLATFORM_ID) private platformId: Object,
){
    if (isPlatformBrowser(this.platformId)) {
       // Your client side code
    }
}

这个方法设置起来太难了,需要浏览所有有导航器的地方,window localstorage ...然后修改。

可以在 server.ts 的上游完成,请遵循 link : https://www.infragistics.com/products/ignite-ui-angular/angular/components/general/framework-and-features/ssr-rendering.html