簡體   English   中英

Angular 通用 npm 運行服務:ssr 返回“文檔未定義”

[英]Angular Universal npm run serve:ssr returns “document is not defined”

我最近為 Angular 8 實現了 Angular Universal。但是運行npm run serve:ssr返回以下內容:

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)

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

在您的 angular 應用程序的 SSR/通用模式下運行時,客戶端代碼/關鍵字(如DocumentWindowlocalstorage等)將不存在,因為您的第一頁將在服務器上呈現。

window、document、localstorage、navigator 和其他瀏覽器類型 - 在服務器上不存在 - 因此使用它們或任何使用它們的庫(例如 jQuery)將無法在 SSR 模式下工作。

因此,如果在您的代碼中存在任何此類代碼,那么您需要將客戶端代碼包裝在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 的上游完成,請點擊此鏈接: https://www.infragistics.com/products/ignite-ui-angular/angular/components/general/framework-and-features/ssr-rendering.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM