2017-05-07 175 views
9

林JS文件尋找一種方式來訪問外部js文件,我包括在資產/數據文件夾的變量如何包括離子3

低於

是我試圖

放置test.js資產/數據文件夾

test.js加入可變testvar = "heloo from external js";

添加腳本標籤中src/index.html<script src="assets/data/test.js"></script>

app.component.ts我增加進口後這條線; declare var testvar: any;

在構造

加入這一行記錄的值console.log(testvar);

結果錯誤錯誤的ReferenceError:的testvar沒有定義

那麼,如何使用我的js變量在打字稿?

回答

11

該解決方案不僅爲我工作

Put the import js in src/index.html header tag, before the build/polyfills.js and build/main.js (they are in body tag);

例子:我創建了一個文件src/assets/test.jsvar testvar,進口的src/index.html,然後在src/app/app.component.ts宣佈declare var testvar;

test.js

var testvar = "Hello from external js"; 

的index.html

... 
    <link rel="icon" type="image/x-icon" href="assets/icon/favicon.ico"> 
    <link rel="manifest" href="manifest.json"> 
    <meta name="theme-color" content="#4e8ef7"> 

    <!-- cordova.js required for cordova apps --> 
    <script src="cordova.js"></script> 
    <script src="assets/js/test.js"></script> //here, not in body 
... 

app.componet.ts

declare var testvar; 

@Component({ 
    templateUrl: 'app.html' 
}) 
export class MyApp { 
    @ViewChild(Nav) nav: Nav; 
    constructor(private statusbar : StatusBar, splashScreen: SplashScreen) { 
    alert(testvar); 
... 
1

從index.html的刪除它,使用它是這樣的:

import from '../assets/data/test'; 
+0

錯誤沒有了嗎?但如何訪問varibale? – rashidnk

+0

console.log(testvar);未定義 – rashidnk

+0

測試現在是var,而不是testvar – misha130

2

要在misha130的答案擴大。您需要將其導入到您想要的文件中,如下所示:

import * as test from '../assets/data/test' 

這樣您就可以訪問測試變量。

console.log(test.testvar);