[英]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();
}
不要與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.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.