NG-ZORRO / ng-zorro-antd

Angular UI Component Library based on Ant Design
https://ng.ant.design
MIT License
8.87k stars 3.94k forks source link

Calling `new Image()` in server side rendering raises ReferenceError Image is not defined #6559

Closed duongleh closed 3 years ago

duongleh commented 3 years ago

Reproduction link

https://github.com/NG-ZORRO/ng-zorro-antd/blob/master/components/image/image.directive.ts#L110 https://github.com/NG-ZORRO/ng-zorro-antd/blob/master/components/graph/core/minimap.ts#L189 https://github.com/NG-ZORRO/ng-zorro-antd/blob/master/components/upload/upload-list.component.ts#L140

Steps to reproduce

Error is immediately raised when the application is initing in SSR

What is expected?

No error should be raised

What is actually happening?

Looking at the source code in the graph, image, and upload-list component, I can see that a new instance of the class Image is created by doing this:

const img = new Image();

As documented in the MDN spec, Image is just a wrapper around document.createElement('img') which directly accesses the document object which is forbidden for SSR usage.

Environment Info
ng-zorro-antd 11.3.0
Browser Chrome 89

I found a way to solve this problem. Firstly, the document object is injected as follow

@Inject(DOCUMENT) private document: any

and then I can use that document variable to create the image as follow

const img = this.document.createElement('img');

If you accept this solution, I think I can help by creating a PR for this issue.

zorro-bot[bot] commented 3 years ago

Hello @duong-le. We totally like your proposal/feedback, welcome to send us a Pull Request for it. Please fill the Pull Request Template here, provide documentation/test cases if needed and make sure CI passed, we will review it soon. Appreciate it advance and we are looking forward to your contribution!

你好 @duong-le, 我们完全同意你的提议/反馈,欢迎直接在此仓库 创建一个 Pull Request 来解决这个问题。请务必填写 Pull Request 内的预设模板,提供改动所需相应的测试用例、文档等,并确保 CI 通过,我们会尽快进行 Review,提前感谢和期待您的贡献! giphy