javascript - 组件更改后,带有外部 JavaScript 的 Angular 不运行
问题描述
所以我创建了一个 script.service.ts 文件,当我的项目需要时,我将我的 JavaScript 文件注入到不同的组件中。但是,当我只是将脚本链接包含在 index.html 文件中时,我仍然面临创建之前遇到的问题。那个问题是,假设您加载了一个名为“localhost:4200/user”的页面,并且它使用了一个组件,该组件使用外部 JavaScript 文件来激活用户网络摄像头。但是,如果您加载说“一切都会很好” localhost:4200/login”,然后单击一个将您路由到“localhost:4200/user”的按钮,相机功能将不起作用。当然,我只是将此功能用作示例。
但主要问题是,如果您首先加载一个组件,然后从外部文件路由到具有 java 脚本功能的组件,除非您从该组件开始,否则该功能将不起作用。那么,如何在路由更改时强制 Angular 重新加载外部 JavaScript 文件的功能?
我正在使用最新版本的 Angular。提前感谢您的帮助!
解决方案
不要在 angular-cli.json 中加载脚本,而是将 app.component.ts 更改为:
import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
constructor(
private router: Router,
private authenticationService: AuthenticationService
) {
}
ngOnInit() {
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
if (document.getElementById('custom_js') !=null) {
document.getElementById('custom_js').remove();
}
const node = document.createElement('script');
node.src = 'assets/js/custom_scripts.js';
node.type = 'text/javascript';
node.async = false;
node.id = 'custom_js';
node.charset = 'utf-8';
document.getElementsByTagName('head')[0].appendChild(node);
}
});
}
}
这将在每次路由后重新插入 js 文件。无需在每个组件中加载脚本。这会变魔术!!!
推荐阅读
- javascript - 在映射数组时在我的“返回”中包含异步函数的结果
- keyman - keyman.setDefaultKeyboardForControl(Pelem, 键盘, languageCode); 函数不适用于 iframe 元素
- shopify - Shopify 商店上的 Klarna Express 按钮
- java - 如何从一个简单的java类调用javacc解析器并执行
- javascript - 防止同时插入大于最大值的值限制为小数
- c# - 每次我按“开始”时,C# autoclicker 都会崩溃
- json - 参数类型'列表
?不能分配给参数类型“列表” ' - mysql - MySQL 在进行数据库备份和迁移时挂断
- pointers - 如何在 C++ 中的 struct 中创建大小未知的动态分配数组
- mongodb - 如何将猫鼬初始化模型与对象数组一起使用