orizens / ngx-infinite-scroll

Infinite Scroll Directive for Angular
https://www.npmjs.com/package/ngx-infinite-scroll
MIT License
1.25k stars 224 forks source link

`hasWindowDefined` can be `true` value in SSR. #397

Closed leo6104 closed 4 months ago

leo6104 commented 2 years ago

Hello. I found some errors in SSR and its root cause is came from ngx-infinite-scroll

To compatible with many libraries in SSR, we use 'jsdom' to mocking window object in Node JS Environment. It means we inject window variable in global variable like this.

const jsdom = require('jsdom');
const win = new jsdom.JSDOM(template);
global['window'] = win.window;

In Angular Universal, they recommends to inject window object to pass compile with using many 3rd party libraries. So, it is common use-case for angular user.

Here is the error i found.

ERROR TypeError: Cannot read property 'documentElement' of undefined
    at getDocumentElement (/.../dist-mobile/server/37.js:4535:53)
    at getElementHeight (/.../dist-mobile/server/37.js:4603:21)
    at calculatePointsForWindow (/.../dist-mobile/server/37.js:4556:31)
    at calculatePoints (/.../dist-mobile/server/37.js:4540:30)
    at createScroller (/.../dist-mobile/server/37.js:4766:20)
    at /.../dist-mobile/server/37.js:4888:32
    at _ZoneDelegate.invoke (/.../dist-mobile/server/main.js:146416:26)
    at Zone.run (/.../dist-mobile/server/main.js:146178:43)
    at NgZone.runOutsideAngular (/.../dist-mobile/server/main.js:228518:28)
    at InfiniteScrollDirective.setup (/.../dist-mobile/server/37.js:4887:17)
    at InfiniteScrollDirective.ngAfterViewInit (/.../dist-mobile/server/37.js:4862:12)
    at callHook (/.../dist-mobile/server/main.js:205613:22)
    at callHooks (/.../dist-mobile/server/main.js:205582:17)

https://github.com/orizens/ngx-infinite-scroll/blob/master/projects/ngx-infinite-scroll/src/lib/ngx-infinite-scroll.directive.ts#L73 I think it can be fixed with checking isPlatformBrowser in here.

  setup() {
    if (hasWindowDefined()) {

to be

  setup() {
    if (hasWindowDefined() && isPlatformBrowser(this.platformId)) {
orizens commented 2 years ago

feel free to open a pr