将 JavaScript 文件添加到 Angular 4 组件

Edd*_* II 1 javascript typescript angular

假设我制作了一个自定义 JavaScript 文件,即“custom.js”

我将如何将其实现到组件中?

如果我将“custom.js”添加到 index.html,那很好,但是有什么方法可以将它专门添加到组件中?

sol*_*... 6

步骤:1 =>在/app文件夹中创建并编写你的 js 代码,比如“ synapse.js ” 。您在组件中使用的函数或常量应该使用关键字导出。例如export

突触.js

export function synapseThrow() {
  return 'hello'
}

export const MY_VAR = 'world!';
Run Code Online (Sandbox Code Playgroud)

步骤:2 => 在angular-cli.json 中,在object.json中添加以下部分apps

"scripts": ["app/synapse.js"]
Run Code Online (Sandbox Code Playgroud)

步骤:3 => 在tsconfig.json 中,在compilerOptions.

"allowJs": true
Run Code Online (Sandbox Code Playgroud)

步骤:4 =>在“任何组件发言权app.component.ts ”导入“ synapse.js使用”文件import的关键字。

app.component.ts

// other imports

import { MY_VAR, synapseThrow } from './synapse';

// other app code here

ngOnInit(){
  const returned = MY_VAR;
  const returnFunc = synapseThrow();
}
Run Code Online (Sandbox Code Playgroud)