我有一个问题,我需要使用特定的第三方库来生成一个nonce来使用square connect api。我很难找到如何加载外部JavaScript库,因为他们没有像我通常那样可以加载的node_module。通过外部库我的意思是像这样的<script src="https://js.squareup.com/v2/paymentform " type="text/javascript">
我没有找到一个很好的方法将其加载到我的应用程序,以便我可以使用它。关于如何解决这个问题的任何想法?
我使用的一些选项:
"scripts": [
"global-script.js",
{ "input": "lazy-script.js", "lazy": true },
{ "input": "pre-rename-script.js", "output": "renamed-script" },
]
import { NgModule } from '@angular/core';
...
require('chart.js');
require('../../libs/chartjs-plugin-annotation');
...
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
第一种方法:
请参阅angular-cli.json
文件中的脚本。
"scripts": [
"../path"
];
第二种方法
您可以创建自己的指令来加载脚本,如下所示
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);
}
}
如何使用
<i appLoadScript [script]="'https://js.squareup.com/v2/paymentform'"></i>