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

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

问题描述

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

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

我已经解决了相关问题

  • How can i import external js file in Angular 5?
  • How to include external js file in Angular 4 and call function from angular to js

我的外部JS(external.js)

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)
}

我在脚本块下的angular.json中添加了所述JS文件

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

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

在CircleComponent中,我想调用该方法

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.

注意:所说的方法只是一个示例方法,我想用复杂的代码文件实现此逻辑.上面提到的问题是关于types.d.ts的,但是我不知道Angular项目中的types.d.ts在哪里.请简要介绍一下.如果上述问题给出了好的解决方法,那我为什么要发布这个问题.

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 CLI创建)

Angular Structure (Created using Angular CLI)

我不知道typings.d.ts在哪里,谁能告诉我在哪里types.d.ts-在上述问题中提到的

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天全站免登陆