[英]How to access external javascript file from angular 2 component
I am very new to angular and front end web development, so maybe i am missing something basic but i did not succeed to search a solution for that issue. 我对角度和前端Web开发非常陌生,因此也许我缺少一些基本知识,但我没有成功找到该问题的解决方案。
according to that answer: Call pure javascript function from Angular 2 component 根据该答案: 从Angular 2组件调用纯JavaScript函数
and following that example 然后跟随那个例子
I am trying to import external .js file to my angular component: 我正在尝试将外部.js文件导入到我的角度组件中:
import '../../../src/Plugin/codemirror/mode/custom/custom.js'
@Component({
selector: 'txt-zone',
templateUrl: 'app/txtzone/Txtzone.component.html',
styleUrls: ['app/txtzone/TxtZone.css'],
})
the path is the correct relative path, i know that because if it loads diractly from the url text box via the browser [http://localhost:50371/src/Plugin/codemirror/mode/custom/custom.js]
i can see the file content... 该路径是正确的相对路径,我知道,因为如果它是通过浏览器[http://localhost:50371/src/Plugin/codemirror/mode/custom/custom.js]
从url文本框中加载的,文件内容...
this is the exception that the chrome debugger is throwing: chrome调试器抛出的异常是:
zone.js:2263 GET http://localhost:50371/src/Plugin/codemirror/lib/codemirror 404 (Not Found) zone.js:2263 GET http:// localhost:50371 / src / Plugin / codemirror / lib / codemirror 404(未找到)
as you can see the path was changed (don`t understand why?) 如您所见,路径已更改(不明白为什么?)
1. how can i solve this issue? 1.我该如何解决这个问题?
2. why the path of the .js file is not the referenced path? 2.为什么.js文件的路径不是引用的路径?
3. maybe there is a better way to load external .js file into my component? 3.也许有更好的方法将外部.js文件加载到我的组件中?
it looks quite trivial question but after hours of searching i could not find any answer. 它看起来很琐碎的问题,但经过数小时的搜索,我找不到任何答案。
A simple way to include custom javascript functions in your Angular 4 project is to include the item in your assets folder, and then use require
to import it into your component typescript. 在Angular 4项目中包含自定义javascript函数的一种简单方法是将该项目包含在资产文件夹中,然后使用require
将其导入到组件打字稿中。
src/assets/example.js src / assets / example.js
export function test() {
console.log('test');
}
src/app/app.component.ts src / app / app.component.ts
(before @Component(...)
) (在@Component(...)
之前)
declare var require: any;
const example = require('../assets/example');
(inside export class AppComponent implements OnInit { ...
) (在export class AppComponent implements OnInit { ...
内部export class AppComponent implements OnInit { ...
)
ngOnInit() {
example.test();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.