In a current project I am implementing Angular server side rendering on a Nrwl/Nx workspace. I went strictly after these guidelines from Nrwl. Everything works fine until running the node application. The project contains an external library called Plotly.js which unfortunately utilizes the document
. It throws the following error
/Users/PATHTOPROJECT/node_modules/plotly.js/dist/plotly.js:105975
var style = document.getElementById(id);
^
ReferenceError: document is not defined
Plotly.js is imported in the lazy-loaded NgModule
import * as PlotlyJS from 'plotly.js/dist/plotly.js';
import { PlotlyModule } from 'angular-plotly.js';
PlotlyModule.plotlyjs = PlotlyJS;
Of course in SSR the document
is not available. Plotly.js is only used in a lazy loaded route. I've tried to guard this route to be only available on isPlatformBrowser
but that does not solve the problem. Maybe there is the possibility to add a "fake" document
or something like that?
Do you have any ideas? Thanks and cheers!
Most important you need is: https://github.com/angular/angular/blob/9b9116c79d626b6356f3dfe0d48c9d990ac412a2/packages/platform-browser/src/browser.ts#L100
But im to low experienced to show you how to make custom BrowserModule.withServerTransition()
You can read documentation and try by your self.
Here you have sollution how to import librarys to component using ngAfterViewInit()
: https://stackoverflow.com/a/51150552/6310260
Because you want to manipulate styles. This is one of a way it will work on SSR:
template:
<div [ngStyle]="setStyle(item.img)"></div>
component.ts
setStyle(imgUrl: string) {
return {
'background-image': `url('${imgUrl}')`,
'background-position': 'center',
'background-repeat': 'no-repeat',
'background-size': 'cover'
}
}
Second one: try "lifecycle-hook" ngAfterViewInit()
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.