【问题标题】:How to access external javascript file from angular 2 component如何从 Angular 2 组件访问外部 javascript 文件
【发布时间】:2018-03-19 22:05:04
【问题描述】:

我对 Angular 和前端 Web 开发非常陌生,所以也许我遗漏了一些东西 基本但我没有成功搜索到该问题的解决方案。

根据那个答案:Call pure javascript function from Angular 2 component

然后example

我正在尝试将外部 .js 文件导入到我的 Angular 组件中:

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

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


})

路径是正确的相对路径,我知道这是因为如果它通过浏览器从 url 文本框直接加载 [http://localhost:50371/src/Plugin/codemirror/mode/custom/custom.js] 我可以看到文件内容...

这是 chrome 调试器抛出的异常:

zone.js:2263 获取 http://localhost:50371/src/Plugin/codemirror/lib/codemirror404(不是 找到)

如您所见,路径已更改(不明白为什么?)

1. 我该如何解决这个问题?
2.为什么.js文件的路径不是引用路径?
3. 是否有更好的方法将外部 .js 文件加载到我的组件中?

这个问题看起来很简单,但经过几个小时的搜索,我找不到任何答案。

【问题讨论】:

  • 检查这个LINK它有一个关于使用类型和没有类型导入js的问题Alos你可以看看这个answer

标签: javascript angular typescript


【解决方案1】:

在您的 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 { ... 内)

ngOnInit() {
  example.test();
}

【讨论】:

  • 感谢您的回答,但它不起作用,如果我声明:const example = require('../../assets/example'); 调试器正在抛出:http://localhost:50371/src/assets/example 404 (Not Found),如果我声明:const example = require('../../assets/example.js'); 调试器正在抛出:zone.js:2263 GET http://localhost:50371/src/traceur 404 (Not Found) (? )
  • @jonathana 这是一种奇怪的行为,听起来它植根于您的编译器而不是您的实际代码。你在使用 Angular-CLI 来构建你的项目吗?
  • 不,我正在使用 Visual Studio,我认为这是问题所在
  • 这绝对是问题所在。我强烈建议您提出一个特定于 Visual Studio 的新问题,因为我们已将其范围缩小到该问题。我正在仔细查看您的问题示例,这应该适用于一般环境。唯一的问题是 Visual Studio 无法识别外部文件。
猜你喜欢
  • 2019-12-13
  • 1970-01-01
  • 2011-02-25
  • 2018-03-13
  • 2019-03-14
  • 2018-11-09
  • 2017-10-27
  • 1970-01-01
  • 2016-02-22
相关资源
最近更新 更多