簡體   English   中英

如何從angular 2組件訪問外部javascript文件

[英]How to access external javascript file from angular 2 component

我對角度和前端Web開發非常陌生,因此也許我缺少一些基本知識,但我沒有成功找到該問題的解決方案。

根據該答案: 從Angular 2組件調用純JavaScript函數

然后跟隨那個例子

我正在嘗試將外部.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文本框中加載的,文件內容...

chrome調試器拋出的異常是:

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

如您所見,路徑已更改(不明白為什么?)

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

它看起來很瑣碎的問題,但經過數小時的搜索,我找不到任何答案。

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

src / assets / example.js

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

src / app / app.component.ts

(在@Component(...)之前)

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

(在export class AppComponent implements OnInit { ...內部export class AppComponent implements OnInit { ...

ngOnInit() {
  example.test();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM