首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在没有全局URL和变量情况下在angular中加载外部脚本

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

Stack Overflow用户
提问于 2021-10-28 20:35:05
回答 1查看 37关注 0票数 0

我需要找到一种安全的方法来加载外部javascript通过URL到角度网络应用程序没有全局url字符串或变量定义。

here我发现这个方法真的很好,没有安全问题:

代码语言:javascript
复制
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定义为:

代码语言:javascript
复制
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和全局变量。有没有办法绕过这里的全局定义?谢谢!

EN

回答 1

Stack Overflow用户

发布于 2021-10-28 21:57:33

如果你不想要全局变量,那么你需要一个数据库。使用像google firebase这样的东西来存储数据并从数据库中检索它。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69760593

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档