簡體   English   中英

Angular中如何使用外部js的方法

[英]How to use methods from external js in Angular

我需要從外部 js 文件調用 function 到我的 Angular 組件中

我已經通過相關問題 go

我的外部 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 文件

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

在 CircleComponent 中,我想調用方法

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

但它未能調用該方法。 請幫助我如何實現這一目標。

注意:上述方法只是一個示例方法,我想用復雜的代碼文件來實現這個邏輯。 上述問題講述了 typings.d.ts,但我不知道我的 Angular 項目中的 typings.d.ts 在哪里。 請介紹一下情況。 如果上述問題給出了很好的解決方法,我為什么要發布這個問題。

Angular 結構(使用 Angular CLI 創建)

在此處輸入圖像描述

我不知道typings.d.ts在哪里,誰能告訴我 typings.d.ts 在哪里 - 在上述問題中提到了How to include external js file in Angular 4 and call function from angular to js

您可以按照以下步驟操作

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

將外部.js文件放在構建腳本中

像那樣

如果仍然看不到它里面的方法放在index.html中

<script src="assets/PATH_TO_YOUR_JS_FILE"></script>

在導入后組件中

declare var FUNCTION_NAME: any;

ANY_FUNCTION() {
    FUNCTION_NAME(params);
}

不要與typings.d.ts混淆。 請遵循以下步驟。

1.將外部文件添加到assets文件夾中。 默認情況下,此文件的內容將根據您的angular-cli.json包含在內。

2.您將要使用的js函數必須exported

export function hello() {
    console.log('hi');
}

3.如下所示將文件導入組件。

 import * as ext from '../assets/some-external.js';

4.現在你可以像引用它了

ext.hello();
Steps:-
1. create a external js file. 
2. In component.ts use the below code.

ngOnInit() {  
  this.loadJsFile(JsFilePath);  
}  
public loadJsFile(url) {  
  let node = document.createElement('script');  
  node.src = url;  
  node.type = 'text/javascript';  
  document.getElementsByTagName('head')[0].appendChild(node);  
} 

3. If u use jquery then define selector in html to render. Or store data in variable.
  1. 確保必須在 index.html 中添加 jquery cdn,並且必須從 npm 安裝 Jquery 及其類型 package。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM