2017-10-08 124 views
0

我對角度和前端Web開發很新,所以也許我錯過了一些基本的東西 ,但我沒有成功搜索該問題的解決方案。如何從角度2組件訪問外部JavaScript文件

根據這個問題的答案:Call pure javascript function from Angular 2 component

並遵循example

我試圖引入外部js文件到我的角度成分:

import '../../../src/Plugin/codemirror/mode/custom/custom.js' 

@Component({ 
    selector: 'txt-zone', 
    templateUrl: 'app/txtzone/Txtzone.component.html', 
    styleUrls: ['app/txtzone/TxtZone.css'], 


}) 

的路徑是正確的相對路徑,我知道,因爲如果它通過瀏覽器[http://localhost:50371/src/Plugin/codemirror/mode/custom/custom.js] 從url文本框加載dirally我可以看到文件內容...

這是鉻調試器拋出異常:

zone.js:2263 GET http://localhost:50371/src/Plugin/codemirror/lib/codemirror 404(未找到 )

正如你所看到的路徑被改變(唐不明白爲什麼?)

1.我該如何解決這個問題?
2.爲什麼.js文件的路徑不是引用路徑?
3.也許有更好的方法來加載外部.js文件到我的組件?

它看起來相當微不足道的問題,但經過幾個小時的搜索我找不到任何答案。

+0

檢查此[鏈接](https://rahulrsingh09.github.io/AngularConcepts/faq)它具有與進口使用類型的JS和不typesAlos一個問題,你可以看看這個[答案] (https://stackoverflow.com/questions/45339209/jquery-is-not-defined-in-bootstrap-sass/45387777#45387777) –

回答

2

在Angular 4項目中包含自定義JavaScript函數的一種簡單方法是將該項目包含在資產文件夾中,然後使用require將其導入到組件打字稿中。

的src /資產/ example.js

export function test() { 
    console.log('test'); 
} 

SRC /應用/ app.component.ts

(前@Component(...)

declare var require: any; 
const example = require('../assets/example'); 

(在內)

ngOnInit() { 
    example.test(); 
} 
+0

謝謝你的答案,但它不工作,如果我聲明:'const example = require('../../ assets/example');'調試器正在拋出:'http:// localhost:50371/src/assets/example 404(Not Found)',如果我聲明:'const example = require('../../ assets/example.js');'debugger is throwing:'zone.js:2263 GET http:// localhost:50371/src/traceur 404(Not Found)'(?) – jonathana

+0

@jonathana這是奇怪的行爲,聽起來像植根於此你的編譯器,而不是你的實際代碼。你使用Angular-CLI來建立你的項目嗎? –

+0

不,我使用視覺工作室,我認爲這是問題 – jonathana