如何在 Angular 中使用来自外部 js 的方法 [英] How to use methods from external js in Angular

查看:28
本文介绍了如何在 Angular 中使用来自外部 js 的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从外部 js 文件调用一个函数到我的 Angular 组件中

我已经完成了相关问题

  • 我不知道 typings.d.ts 在哪里,谁能告诉我typings.d.ts 在哪里 - 在上述问题中提到了 如何在 Angular 4 中包含外部 js 文件并将函数从 angular 调用到 js

    解决方案

    您可以按照以下步骤操作

    1) 首先添加外部 JS 文件的引用,以便将其导入组件.import * as wrapperMethods from '../../src/assets/external.js';2)现在声明一个与您的函数在外部JS中具有相同名称的var".声明 var 包装方法:任何;3) ngOninit(){包装方法();}

    I need to call a function from external js file into my Angular component

    I already go through the related question

    My External JS (external.js)

    var radius = 25;
    
    function calculateRadius(pi) {
        let piValue = 3.14159;
    
        if(pi) {
            piValue = pi;
        }
    
        var result = piValue * radius * radius;
        console.log('Result: ', result);
    }
    
    function wrapperMethod(pi) {
        console.log('Hi, this is from wrapper method');
        calculateRadius(pi)
    }
    

    I added the said JS file in the angular.json under scripts block

    "scripts": [
        "src/assets/external.js",
    ]
    

    In the CircleComponent, I would like to call the method

    import wrapperMethod from '../../src/assets/external.js';
    
    @Component({
      selector: 'app-circle',
      templateUrl: './circle.component.html',
      styleUrls: ['./circle.component.css']
    })
    export class CircleComponent implements OnInit {
        constructor() { }
    
        ngOnInit() {
            wrapperMethod(3.14159);
        }
    }
    

    But its failing to call the method. Kindly assist me how to achieve this.

    Note: The said methods as just an example methods, I want to implement this logic with the complex code file. The said question tells about typings.d.ts, but I don't know where is typings.d.ts in my Angular project. Kindly brief me regarding this. If the said question gives good solution means, why should I post this question.

    Angular Structure (Created using Angular CLI)

    I don't know where is typings.d.ts, could anyone please tell me where is typings.d.ts - which is mentioned in the said questions How to include external js file in Angular 4 and call function from angular to js

    解决方案

    You can follow this below steps

    1) First add a reference of your external JS file for importing it to the component. 
       import * as wrapperMethods from '../../src/assets/external.js';
    
    2) Now declare a "var" of the same name that your function has inside external JS.
       declare var wrapperMethods: any;
    
    3) ngOninit(){
        wrapperMethods();
       }
    

    这篇关于如何在 Angular 中使用来自外部 js 的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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