Angular 10 universal | amcharts 4 : Why the server tries to load the chart?

我的梦境 提交于 2021-01-29 19:07:50

问题


I am used to Angular but I am just starting to use universal (for SEO).

I want to use a map from amcharts 4, I have no problems using without Angular Universal. I know that it is a known issue but I do not understand why in my case the server tries to load the chart and create this error:

ERROR Error: Uncaught (in promise): ReferenceError: addEventListener is not defined
ReferenceError: addEventListener is not defined
...

My code :

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

  ngOnInit(): void {
    this.setUpChart();
  }

  setUpChart() {
    if (isPlatformBrowser(PLATFORM_ID)) {
      let chart = am4core.create("world-map", am4maps.MapChart);
      // ...
    }
  }

回答1:


Thanks to David, I found the problems. There where two :

  1. isPlatformBrowser(PLATFORM_ID) => isPlatformBrowser(platformId): Object

  2. The error was indeed in the library so it was occured only outside my condition. This my code now to avoid this problem :


declare var require: any;

@Component({...})
export class MapComponent implements OnInit, OnDestroy {

  private chart;
  isBrowser: boolean

  constructor(
    @Inject(PLATFORM_ID) private platformId: Object
  ) {
    this.isBrowser = isPlatformBrowser(platformId)
  }

  ngOnInit(): void {
    if (this.isBrowser) {
      this.setUpChart();
    }
  }


  setUpChart() {
    if (this.isBrowser) {

      const am4core = require("@amcharts/amcharts4/core");
      const am4maps = require("@amcharts/amcharts4/maps");

      let chart = am4core.create("world-map", am4maps.MapChart);
      // ...
    }
  }


来源:https://stackoverflow.com/questions/62646218/angular-10-universal-amcharts-4-why-the-server-tries-to-load-the-chart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!