[英]How to load External Javascript Libraries into Angular 4 components
I have a problem where I need to use a specific 3rd party library to generate a nonce to use the square connect api.我有一个问题,我需要使用特定的 3rd 方库来生成 nonce 以使用 square connect api。 I am having troubles finding how to load the external javascript library since they don't have a node_module that I can load like I usually do.
我在寻找如何加载外部 javascript 库时遇到了麻烦,因为它们没有我可以像往常一样加载的 node_module。 By external library I mean something like this
<script src="https://js.squareup.com/v2/paymentform " type="text/javascript">
I have not found a good way to to load this into my application so that I can use it.外部库我的意思是这样的
<script src="https://js.squareup.com/v2/paymentform " type="text/javascript">
我还没有找到将它加载到我的应用程序中的好方法,所以我可以使用它。 Any ideas on how I can solve this problem?关于如何解决这个问题的任何想法?
A few options that I have used:我使用过的几个选项:
Global script using angular-cli使用angular-cli 的全局脚本
"scripts": [ "global-script.js", { "input": "lazy-script.js", "lazy": true }, { "input": "pre-rename-script.js", "output": "renamed-script" }, ]
Require in a specific module在特定模块中需要
import { NgModule } from '@angular/core'; ... require('chart.js'); require('../../libs/chartjs-plugin-annotation'); ...
Add a global script at runtime based on some condition根据某些条件在运行时添加全局脚本
if (this.usesCKEditor(permissions) && !window['CKEDITOR']) { const url = '//cdn.ckeditor.com/4.7.3/full/ckeditor.js'; const script = document.createElement('script'); script.type = 'text/javascript'; script.src = url; document.body.appendChild(script); } // must check if the script has loaded before using it
First Approach:第一种方法:
Refer the scripts inside the angular-cli.json
file.请参阅
angular-cli.json
文件中的脚本。
"scripts": [
"../path"
];
Second Approach第二种方法
You can create your own directive to load script as below您可以创建自己的指令来加载脚本,如下所示
import { Directive, OnInit, Input } from '@angular/core';
@Directive({
selector: '[appLoadScript]'
})
export class LoadScriptDirective implements OnInit{
@Input('script') param: any;
ngOnInit() {
let node = document.createElement('script');
node.src = this.param;
node.type = 'text/javascript';
node.async = false;
node.charset = 'utf-8';
document.getElementsByTagName('head')[0].appendChild(node);
}
}
HOW TO USE
如何使用
<i appLoadScript [script]="'https://js.squareup.com/v2/paymentform'"></i>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.