简体   繁体   中英

ReferenceError: window is not defined Angular Universal

I'm using Angular 10 and trying to implement SSR in my project.

When I run the npm run serve:ssr I'm getting the below error

ReferenceError: window is not defined

When I googled, they suggested to add domino

So below is my server.ts

....
const scripts = fs.readFileSync('dist/asfc-web/browser/index.html').toString();

const window = domino.createWindow(scripts);
global['window'] = window;
global['document'] = window.document;

....

still getting the same error, Please guide me how to resolve this issue.

It's simple fix,

I've imported the AppServerModule after the global['window'] and it worked

global['window'] = window;
global['document'] = window.document;

import { AppServerModule } from '../../projects/asfc-web/src/main.server';

you can use Renderer2 listen for this.

import { Renderer2 } from '@angular/core';
 constructor(private renderer2: Renderer2) {
     ...
 }
this.renderer2.listen('window', 'load', event => {    
   this.innerWidth = event.currentTarget.innerWidth;
   console.log(this.innerWidth);
});

You can create new service

import {Injectable} from '@angular/core';

function _window(): any {
  return window;
}

@Injectable({
  providedIn: 'root'
})
export class WindowRef {
  get nativeWindow(): any {
    return _window();
  }
}

add in constructor where you want to use:

  constructor(
    private windowRef: WindowRef
  ) {
  }

and use like this:

  this.windowRef.nativeWindow.scrollTo({
    top: 0,
    behavior: 'smooth'
  });

or you can check platform:

  constructor(
    @Inject(PLATFORM_ID) private platformId: any,
    private windowRef: WindowRef
  ) {
  }
if (isPlatformBrowser(this.platformId)) {
  this.windowRef.nativeWindow.scrollTo({
    top: 0,
    behavior: 'smooth'
  });
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM