Angular 2 : 组件可以访问外部js文件变量

Angular 2 : external js file variables are accessible from component

我正在尝试将外部 js 文件导入我的组件。

external.js

var x=9;

component.ts

import '../../assets/api/external.js';
declare let x: any;
....
console.log(x);

我得到:

ERROR ReferenceError: x is not defined

如何从组件访问 x?它没有抱怨找不到js文件。

请将您的脚本作为全局脚本添加到 angular-cli.json。

 "scripts": [
"../external.js",
"../node_modules/.....min.js",
"../node_modules/jspdf-autotable/dist/....js"
],

如果有帮助请告知。 这是参考 link:https://github.com/angular/angular-cli/wiki/stories-global-scripts

您的导入 js 没有导出任何函数或 class 到您的组件。 MDN接口导入订阅import 'module_name':

Import an entire module for side effects only, without importing anything. This runs the module's global code, but doesn't actually import any values.

所以更改你的并添加 class 或函数然后导出。

您可以在 Angular 应用程序中从 anthoer 脚本调用 varibale。

第 1 步。在 assests/javascript 文件夹中创建 demo.js 文件。

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

第 2 步。在 assests/javascript 文件夹中创建 demo.d.ts 文件。

export declare function test1();

第 3 步。在您的组件中使用它

//User defined file path
import { test1 } from '../assets/javascript/demo'; 
 @Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor() {
    console.log(test1());
  }
}

注意:js和.d.ts文件名要相同