0

Context: I have an Angular 2+ application that makes calls to a web API containing URLs for a src attribute on a script tag that is created by a loadScript function in the AfterViewInit lifecycle hook.

The web API returns a JsonResult and is yielding the data I expect. I was able to interpolate some of the data in the component's template.

Additionally, before I added the call to the web API, the loadScript function was working with a hard-coded argument.

Reading a thread on github. A "member" stated that scripts are not supposed to be loaded on demand. So what I implemented with the loadScript function is essentially a work around, but how else would load them? I don't want to have a seemingly endless amount of script tags sitting in the index.html file.

import { Component, OnInit, AfterViewInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Http } from '@angular/http';

@Component({
    selector: 'app-agriculture-roadmap',
    templateUrl: './agriculture-roadmap.component.html',
    styleUrls: ['./agriculture-roadmap.component.css']
})

export class RoadmapComponent implements OnInit, AfterViewInit {

    constructor(private _httpService: Http, private _route: ActivatedRoute)
    {

    }

    apiRoadmaps: { roadmapName: string, pdfRoadmapURL: string, jsRoadmapURL: string };

    ngOnInit() {   
        this._httpService
            .get('/api/roadmaps/' + this._route.params)
            .subscribe(values => {
                this.apiRoadmaps = values.json() as { roadmapName: string, pdfRoadmapURL: string, jsRoadmapURL: string };
            });
    }

    async ngAfterViewInit() {
        await this.loadScript(this.apiRoadmaps.jsRoadmapURL);
    }

    private loadScript(scriptUrl: string) {
        return new Promise((resolve, reject) => {
            const scriptElement = document.createElement('script')
            scriptElement.src = scriptUrl
            scriptElement.onload = resolve
            document.body.appendChild(scriptElement)
        })
    }
}
Jade Cowan
  • 2,543
  • 1
  • 18
  • 32
  • 1
    one side note, you didn't `resolve` your `loadScript`. You must add `resolve()` after `document.body.appendChild(scriptElement)`. check https://stackoverflow.com/questions/36734900/what-happens-if-we-dont-resolve-or-reject-the-promise – Idrees Khan Aug 05 '17 at 05:13

1 Answers1

0

If you are using angular cli . Then place these scripts in

angular-cli.json file under scripts array

scripts:[
.....
]

Please refer this [link] (https://rahulrsingh09.github.io/AngularConcepts/faq)

It has a question on how to refer third party js or scripts in Angular with or without typings.

Rahul Singh
  • 19,030
  • 11
  • 64
  • 86