2017-10-08 128 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