简体   繁体   English

如何在角度5中调用外部javascript函数?

[英]How to call external javascript function in angular 5?

I have downloaded a theme from this link. 我已经从这个链接下载了一个主题。 I have to define script and CSS in index.html file. 我必须在index.html文件中定义脚本和CSS。

index.html (body section) index.html(正文部分)

<body>
  <app-root></app-root>
  <script type="text/javascript" src="./assets/js/main.85741bff.js"></script>
  <script type="text/javascript" src="./assets/js/common.js"></script>
</body>

I have defind my function in common.js and call it from main.85741bff.js file. 我在common.js中定义了我的函数,并从main.85741bff.js文件中调用它。

common.js (function) common.js(function)

document.addEventListener("DOMContentLoaded", function (event) {
     masonryBuild();
     navbarToggleSidebar();
     navActivePage();
});

The issue is that I am able to call the function while page reloads but can't call the function while content load. 问题是我可以在页面重新加载时调用该函数,但在内容加载时无法调用该函数。

Can anyone help me to resolve this issue? 任何人都可以帮我解决这个问题吗? Any help would be appreciated. 任何帮助,将不胜感激。

You can use javascript in the Angular application. 您可以在Angular应用程序中使用javascript。

Step 1. Create demo.js file in assets/javascript folder. 步骤1.在assets / javascript文件夹中创建demo.js文件。

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

Step 2. Create demo.d.ts file in assets/javascript folder. 步骤2.在assets / javascript文件夹中创建demo.d.ts文件。

export declare function test1();

Step 3. Use it in your component 步骤3.在组件中使用它

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());
  }
}

Note: js and .d.ts file name should be same 注意:js和.d.ts文件名应该相同

You need to change the order in which you load your JavaSciprt files. 您需要更改加载JavaSciprt文件的顺序。 Try loading common.js before main......js . 尝试在main......js之前加载common.js Your script tries to access a function from a file that hasn't been loaded yet. 您的脚本尝试从尚未加载的文件中访问函数。 Try just switching those two lines of code: 尝试只切换这两行代码:

<body>
  <app-root></app-root>
  <script type="text/javascript" src="./assets/js/common.js"></script>
  <script type="text/javascript" src="./assets/js/main.85741bff.js">/script>
</body>

In Angular4, 5 project folder, there is .angular-cli.json file. 在Angular4,5项目文件夹中,有.angular-cli.json文件。

In file, you will see 在文件中,您将看到

"apps": [
  {
    "scripts": []
  }
]

push your external js file path in the array. 在数组中推送外部js文件路径。

You can call these methods by window object- 你可以通过window object调用这些方法 -

document.addEventListener("DOMContentLoaded", function (event) {
      window['navbarToggleSidebar']();
      window['navActivePage']();
 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM