如何将外部 Javascript 库加载到 Angular 4 组件中 [英] How to load External Javascript Libraries into Angular 4 components

查看:29
本文介绍了如何将外部 Javascript 库加载到 Angular 4 组件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,我需要使用特定的 3rd 方库来生成 nonce 以使用 square connect api.我在寻找如何加载外部 javascript 库时遇到了麻烦,因为它们没有我可以像往常一样加载的 node_module.通过外部库,我的意思是这样的 <script src="https://js.squareup.com/v2/paymentform " type="text/javascript"> 我还没有找到一个好的将其加载到我的应用程序中以便我可以使用它的方法.关于如何解决这个问题的任何想法?

解决方案

第一种方法:

参考 angular-cli.json 文件中的脚本.

脚本":[../小路"];

第二种方法

您可以创建自己的指令来加载脚本,如下所示

import { Directive, OnInit, Input } from '@angular/core';@指示({选择器:'[appLoadScript]'})导出类 LoadScriptDirective 实现 OnInit{@Input('script') 参数:任何;ngOnInit() {let node = document.createElement('script');node.src = this.param;node.type = '文本/javascript';node.async = false;node.charset = 'utf-8';document.getElementsByTagName('head')[0].appendChild(node);}}

<块引用>

如何使用

<i appLoadScript [script]="'https://js.squareup.com/v2/paymentform'"></i>

演示

I have a problem where I need to use a specific 3rd party library to generate a nonce to use the 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. 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. Any ideas on how I can solve this problem?

解决方案

First Approach:

Refer the scripts inside the angular-cli.json file.

"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>

DEMO

这篇关于如何将外部 Javascript 库加载到 Angular 4 组件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆