window is not defined angular universal third library

后端 未结 5 706
臣服心动
臣服心动 2021-01-03 03:59

I am working with the library ng2-mqtt and I used it im my component like this:

 import \'ng2-mqtt/mqttws31.js\';
declare var Paho: any;

No

5条回答
  •  攒了一身酷
    2021-01-03 04:06

    UPDATE

    Extending Leon Li's answer, we can avoid loading components that cannot be rendered on server side if it requires Browser APIs like location or window.

    This answer explains how to use

    import { PLATFORM_ID } from '@angular/core';
    import { isPlatformBrowser, isPlatformServer } from '@angular/common';
    
    constructor( @Inject(PLATFORM_ID) platformId: Object) {
      this.isBrowser = isPlatformBrowser(platformId);
    }
    

    Just inject PLATFORM_ID into your service, and pass it to isPlatformBrowser or isPlatformServerto get a Boolean value. Accordingly you can show/hide the components that cannot be rendered on server if they depend on Browser APIs.

提交回复
热议问题