Angular 6 | Server side rendering: issue 'window not defined'

对着背影说爱祢 提交于 2020-01-14 06:26:08

问题


I have updated my application from angular version 5 to latest. Here's detail:

  Angular CLI: 6.2.1
  Node: 8.12.0
  OS: win32 x64
  Angular: 6.1.6

Also I am using this: ng-toolkit-universal to achieve server side rendering. I am able to build application using command "npm run build:prod" , but facing following issue while running command: "npm run server":

Can anyone please help or suggest some soution for the same.

Thanks in advance!


回答1:


Assuming you are done SSR with angular universal. Put following code in your server.ts after imports. Build and run.

const domino = require("domino");
const fs = require("fs");
const path = require("path");
const templateA = fs
  .readFileSync(path.join("dist/browser", "index.html"))
  .toString();
const win = domino.createWindow(templateA);
win.Object = Object;
win.Math = Math;

global["window"] = win;
global["document"] = win.document;
global["branch"] = null;
global["object"] = win.object;
global['HTMLElement'] = win.HTMLElement;
global['navigator'] = win.navigator;
global['localStorage'] = localStorage;


来源:https://stackoverflow.com/questions/52391718/angular-6-server-side-rendering-issue-window-not-defined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!