如何在没有全局URL和变量的情况下加载angular中的外部脚本



我需要找到一种安全的方法,通过URL加载外部javascript到Angular web应用程序,而不需要全局URL字符串或变量定义。

从这里我发现这种方法非常好,没有安全问题:

import { Component, OnInit, Renderer2 } from "@angular/core";
import { ScriptService } from "./services/script.service";
const SCRIPT_PATH = 'https://apis.google.com/js/api.js';
declare let gapi: any;
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
constructor(
private renderer: Renderer2,
private scriptService: ScriptService
) { }

ngOnInit() {
const scriptElement = this.scriptService.loadJsScript(this.renderer, SCRIPT_PATH);
scriptElement.onload = () => {
console.log('Google API Script loaded');
console.log(gapi);
// Load the JavaScript client library.
// (the init() method has been omitted for brevity)
gapi.load('client', this.init);
}
scriptElement.onerror = () => {
console.log('Could not load the Google API Script!');
}
}
}

,其中ScriptService定义为:

import { Renderer2, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';
export class ScriptService {

constructor(
@Inject(DOCUMENT) private document: Document
) { }

/**
* Append the JS tag to the Document Body.
* @param renderer The Angular Renderer
* @param src The path to the script
* @returns the script element
*/
public loadJsScript(renderer: Renderer2, src: string): HTMLScriptElement {
const script = renderer.createElement('script');
script.type = 'text/javascript';
script.src = src;
renderer.appendChild(this.document.body, script);
return script;
}
}

缺点是,它使用全局字符串URL和全局变量。这里是否有绕过全局定义的方法?谢谢!

如果不需要全局变量,则需要数据库。使用类似google firebase的东西来存储数据并从数据库中检索。

最新更新