【问题标题】:External .js file in an Angular 8 projectAngular 8 项目中的外部 .js 文件
【发布时间】:2019-12-20 08:23:28
【问题描述】:

我正在尝试从 Angular 组件调用 .js 文件中的函数,但我收到错误“错误 ReferenceError:myTest 未在 TechnologiesComponent.onClick 中定义”。

我已按照here 中描述的步骤进行操作,因此我在我的 src 文件夹中创建了一个名为 custom.js 的文件。

该文件包含以下内容:

function myTest() {
  alert('Welcome to custom js');
}

$(function() {
  alert('Hello, custom js');
});

我已经在我的 angular.json 中的脚本数组中添加了脚本,如下所示:

        "tsConfig": "tsconfig.app.json",
        "aot": false,
        "assets": [
          "src/assets"
        ],
        "styles": [
          "src/styles.css"
        ],
        "scripts": ["src/custom.js"]
      },

我要在其中使用 .js 文件的 .ts 文件如下所示:

import { Component } from '@angular/core';

declare const myTest: any;

@Component({
  selector: 'app-technologies',
  templateUrl: './technologies.component.html',
  styleUrls: ['./technologies.component.css']
})
export class TechnologiesComponent {
  onClick() {
    myTest();
  }
}

我的模板中添加了一个按钮: 点我

按下按钮时,会抛出错误“ERROR ReferenceError: myTest is not defined at TechnologiesComponent.onClick”。为什么?

【问题讨论】:

标签: javascript angular


【解决方案1】:

将你的函数声明为变量(在 JS 中两者是相同的)

custom.js

myTest = function(){
   alert('Welcome to custom js');
}

另外,验证脚本是否在最终构建中被导入

如果您使用 ng serve

,您可能需要重新构建

【讨论】:

  • 将函数声明为变量并不是一个真正的选择,因为我要导入一个大型的第三方库。 custom.js 只是为了拥有一个 MWE。但我正在使用 ng serve,简单地重建解决了我的问题。谢谢:)
  • 很好,我添加了对你有帮助的额外行,我们都陷入了同样的境地:)
【解决方案2】:

如果您想在 .ts 文件中使用 .js 文件中的代码,您应该使用 exportimport。 您的项目示例:

custom.js

export function myTest() {
  alert('Welcome to custom js');
}

app.component.ts

import {Component} from '@angular/core';
import * as custom from 'src/custom.js';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  onClick() {
    custom.myTest();
  }
}

注意import * as custom from 'src/custom.js';这一行 这是从非 ts 文件中导入 smth 的最佳方法之一。

结构:

【讨论】:

    【解决方案3】:

    我正在使用 Angular 10 并尝试访问平面 js 文件,并且不允许更改 js 文件 即无法在其中添加export

    1. angular.json中添加你的js文件

    1. 我想从myJs.js 以角度访问print() 函数,就像

    // MyJS.js
    
    function print(a){
    cosole.log(a +" Code from JS");
    }
    1. app.component.ts

    import {Component} from '@angular/core';
      
     // following variable name and function name in js file should be same
    declare var print: any;
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
    
      onClick() {
       print('Yes');
      }
    }
    1. 然后再次触发 ng serve

    (如果仍然不适合您,请尝试将您的 js 文件放入 assets 文件夹并更改 angular.json 中的路径)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-29
      • 2017-04-28
      • 2014-09-15
      相关资源
      最近更新 更多