Angular 9.1.1 允许 Angular 组件访问主和运行时包外部的 JavaScript 文件,这通常是通过在 Angular 应用程序中引入外部脚本文件来实现的。以下是一些基础概念和相关信息:
src
目录下的 JavaScript 文件,可能来自第三方库或其他来源。window
对象访问。angular.json
中配置在 angular.json
文件中,可以在 scripts
数组中添加外部脚本的路径:
{
"projects": {
"your-project-name": {
"architect": {
"build": {
"options": {
"scripts": [
"path/to/your/external-script.js"
]
}
}
}
}
}
}
在 Angular 组件中,可以使用 Renderer2
服务动态创建 <script>
标签并添加到 DOM 中:
import { Component, Renderer2, OnInit } from '@angular/core';
@Component({
selector: 'app-your-component',
templateUrl: './your-component.component.html',
styleUrls: ['./your-component.component.css']
})
export class YourComponent implements OnInit {
constructor(private renderer: Renderer2) {}
ngOnInit() {
const script = this.renderer.createElement('script');
script.type = 'text/javascript';
script.src = 'path/to/your/external-script.js';
this.renderer.appendChild(document.body, script);
}
}
原因:
解决方法:
原因:
解决方法:
window
对象访问全局变量或函数,例如 window.myFunction()
。假设我们有一个外部 JavaScript 文件 external-script.js
,其中定义了一个全局函数 myFunction
:
// external-script.js
window.myFunction = function() {
console.log('External function called!');
};
在 Angular 组件中调用这个函数:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-your-component',
templateUrl: './your-component.component.html',
styleUrls: ['./your-component.component.css']
})
export class YourComponent implements OnInit {
ngOnInit() {
if (window.myFunction) {
window.myFunction();
} else {
console.error('myFunction is not defined');
}
}
}
通过以上方法,你可以成功地在 Angular 9.1.1 中引入和使用外部 JavaScript 文件。
领取专属 10元无门槛券
手把手带您无忧上云