window is not defined angular universal third library

后端 未结 5 730
臣服心动
臣服心动 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条回答
  •  Happy的楠姐
    2021-01-03 04:23

    Follow these two steps:

    1. Use PLATFORM_ID injection in your components to detect whether it is browser platform or server platform as below:

      constructor(
          @Inject(DOCUMENT) private document: Document,
          @Inject(PLATFORM_ID) private platformId: any) {}
      
      ngOnInit() {
          this.scrollToTop();
      }
      
      scrollToTop() {
          if (isPlatformBrowser(this.platformId)) {
              // your code
          }
      }
      

    But this strategy will work for code which we write ourselves, but what if we are using a third party library which accesses window, document or other DOM globals?

    JavaScript within a third party library may throw errors due to attempting to access these globals during our server render, but we have no control over the library’s code. In this case we can install a library such as domino, and then create a shim for the window and document objects in the server

    1. Install domino and use it as this in your server.ts file

提交回复
热议问题