'Load js scrips on component variable already in use

I have an angular app, and one component has to load some javascript files from assets. These scripts are loading some data into some graphs on my component page. When I click on a point on the graph, I get redirected to another component.

This is how I am loading the scripts:

loadAPI: Promise<any>;

  constructor(private router: Router,
    private route: ActivatedRoute,
    private communicationService: ComunicationService
  ) {
    this.route.params.subscribe(params => {
      this.name = params["name"];
      communicationService.emitToolbarNameChange("myPage");
    });
    this.loadAPI = new Promise((resolve) => {
      this.loadScript1();
      resolve(true);
    });
  }

public loadScript1() {
      var isFound = false;
      var scripts = document.getElementsByTagName("script")
      for (var i = 0; i < scripts.length; ++i) {
          if (scripts[i].getAttribute('src') != null && scripts[i].getAttribute('src').includes("loader")) {
              isFound = true;
          }
      }

      if (!isFound) {
          var dynamicScripts = ["../../../../assets/js/main.js","../../../../assets/js/1.js","../../../../assets/js/2.js",
        "../../../../assets/js/3.js","../../../../assets/js/4.js","../../../../assets/js/5.js",
      "../../../../assets/js/6.js","../../../../assets/js/7.js","../../../../assets/js/8.js","../../../../assets/js/9.js"];

          for (var i = 0; i < dynamicScripts.length; i++) {
              let node = document.createElement('script');
              node.src = dynamicScripts [i];
              node.type = 'text/javascript';
              node.async = false;
              node.charset = 'utf-8';
              document.getElementsByTagName('head')[0].appendChild(node);
          }

      }
    }

The problem is I have to define the variables as var's in the js files, I believe they are overwritten each time I access the component page. If I have them as let, they work one time then I get errors in the console that they are already used.

If I load the scripts in the index.html or in build { ..., scripts []} no data is shown on the page. I am redirecting from my component page and from that page back to the component page.

Any suggestions on how to load the scripts?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source