亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Angular2:將外部js文件導入組件

Angular2:將外部js文件導入組件

慕村225694 2019-12-20 10:19:08
我將將此d3gauge.js文件導入我的angular2組件memmon.component.ts文件之一。import '../../../../js/d3gauge.js';export class MemMonComponent {    createMemGauge() {        new drawGauge(this.opt);  //drawGauge() is a function inside d3gauge.js    }}然后在相應的模板文件中添加<script src="../../../../js/d3gauge.js"></script>但這是行不通的,drawGauge無法找到。所以,將外部js文件導入angular2的正確步驟是什么?由于我使用的是webpack,是否可以在webpack中進行?我指的是這個問題,由于無法解決,因此webpack解決方案對我不起作用.ensure。
查看完整描述

3 回答

?
動漫人物

TA貢獻1815條經驗 獲得超10個贊

理想情況下,您需要具有.d.ts鍵入文件才能Linting正常工作。


但是似乎d3gauge沒有,您可以要求開發人員提供并希望他們會聽。


或者,您可以通過執行以下操作解決此特定問題


declare var drawGauge: any;


import '../../../../js/d3gauge.js';

export class MemMonComponent {

    createMemGauge() {

        new drawGauge(this.opt);  //drawGauge() is a function inside d3gauge.js

    }

}

如果您在多個文件中使用它,則可以d3gauage.d.ts使用以下內容創建文件


declare var drawGauge: any;

并boot.ts在頂部的(bootstrap)文件中引用它,就像這樣


///<reference path="../path/to/d3gauage.d.ts"/>


查看完整回答
反對 回復 2019-12-20
?
喵喔喔

TA貢獻1735條經驗 獲得超5個贊

在浪費大量時間尋找解決方案之后,我找到了一個。為了方便起見,我使用了完整的代碼,可以用它替換整個文件。


這是一個普遍的答案。假設您要將名為testjs.js的文件導入您的angular 2組件。在您的資產文件夾中創建testjs.js:


資產> testjs.js


function test(){

    alert('TestingFunction')

}

在您的index.html中包含testjs.js


index.html


<!doctype html>

<html>

<head>

  <meta charset="utf-8">

  <title>Project1</title>

  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="icon" type="image/x-icon" href="favicon.ico">


  <script src="./assets/testjs.js"></script>


</head>

<body>

  <app-root>Loading...</app-root>

</body>

</html>

在您要調用此js的app.component.ts或任何component.ts文件中,聲明一個變量并調用如下函數:


app.component.ts


import { Component } from '@angular/core';


declare var test: any;



@Component({

  selector: 'app-root',

  templateUrl: './app.component.html',

  styleUrls: ['./app.component.css']

})


export class AppComponent {

  title = 'app works!';



  f(){

    new test();

  }

}

最后在您的app.component.html中測試功能


app.component.html


<h1>

  <button (click)='f()'>Test</button>

</h1>


查看完整回答
反對 回復 2019-12-20
?
小怪獸愛吃肉

TA貢獻1852條經驗 獲得超1個贊

您可以在文件中包含js擴展名,而不必在中添加文件擴展名。index.html.angular-cli-json


這些是我執行此步驟的步驟:


首先將您的外部js文件包含在assets/js

在.angular-cli.json-在腳本下添加文件路徑: [../app/assets/js/test.js]

在要使用js文件功能的組件中。

在頂部將文件導入為聲明


declare const Test:any;

之后,您可以訪問其功能,例如 Test.add()


查看完整回答
反對 回復 2019-12-20
  • 3 回答
  • 0 關注
  • 1427 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號