0

I am using javascriptservices template with angular2+, and I am trying to find a solution for importing libraries into my component that try to access window. Javascript services use server-side pre-rendering, so you cannot import libraries into components that immediately try to access window without getting window is not defined error.

Currently, I am trying to add dat.gui to my component, but I have not found a solution. https://www.npmjs.com/package/dat.gui

Does anybody know of a way that I can load the dat.gui library on the client-side, and pass it to my component to avoid the window is not defined error when importing it into a component?

This will always throw an error when added to my component because of the server side pre-rendering.

const dat = require('dat.gui');
const gui = new dat.GUI();

Or Import * as dat from ‘dat.gui’;

Iman Bahrampour
  • 6,180
  • 2
  • 41
  • 64
Chris
  • 153
  • 2
  • 15
  • In my case I use to pass params from server to client side and tried to read it on client then this occurs. in your case you just importing from its module right? – k11k2 Feb 27 '18 at 05:16
  • K11k2 that is correct I am importing it from the module. Are you saying your method does not work? – Chris Feb 27 '18 at 06:07
  • let me know what exactly let you this error so add code which you have tried. – k11k2 Feb 27 '18 at 06:18
  • The code I listed gave me this error because the server side pre rendering will load my component and the imports inside it. Since the component is being rendered on the server and requires dat.gui, which will need access to the DOM that does not exist it will throw window is undefined error. I am trying to find a solution where I can import the day.gui library after the server pre rendering. – Chris Feb 27 '18 at 06:22
  • then you can set `ngAfterView() {setTimeout(function(){ const dat = require('dat.gui'); const gui = new dat.GUI(); },3000);}` – k11k2 Feb 27 '18 at 06:25
  • That will still cause window is undefined error. – Chris Feb 27 '18 at 18:04

1 Answers1

0

This is how I use to make sure it's the browser to use window, document, navigator, jQuery operations.

  import {PLATFORM_ID} from '@angular/core'
  import {isPlatformBrowser } from '@angular/common'
    ....


    constructor(@Inject(PLATFORM_ID) private platformId: Object){}

    private isBrowser: boolean = isPlatformBrowser(this.platformId);

    ngAfterViewInit(){
      if (this.isBrowser) {
       const dat = require('dat.gui');
       const gui = new dat.GUI();
      }
    }
k11k2
  • 2,036
  • 2
  • 22
  • 36