0

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);
      // ...
    }
  }
  • It's probably that the `addEventListener` code is called when the module is imported, even if you don't instantiate the charts. It depends on how the library is written – David Jun 29 '20 at 20:40
  • You might need to wrap `this.setUpChart()` with a platform check to only execute if it's running in a browser. – Brandon Taylor Jun 29 '20 at 20:54

1 Answers1

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);
      // ...
    }
  }