首页 > 解决方案 > 组件更改后,带有外部 JavaScript 的 Angular 不运行

问题描述

所以我创建了一个 script.service.ts 文件,当我的项目需要时,我将我的 JavaScript 文件注入到不同的组件中。但是,当我只是将脚本链接包含在 index.html 文件中时,我仍然面临创建之前遇到的问题。那个问题是,假设您加载了一个名为“localhost:4200/user”的页面,并且它使用了一个组件,该组件使用外部 JavaScript 文件来激活用户网络摄像头。但是,如果您加载说“一切都会很好” localhost:4200/login”,然后单击一个将您路由到“localhost:4200/user”的按钮,相机功能将不起作用。当然,我只是将此功能用作示例。

但主要问题是,如果您首先加载一个组件,然后从外部文件路由到具有 java 脚本功能的组件,除非您从该组件开始,否则该功能将不起作用。那么,如何在路由更改时强制 Angular 重新加载外部 JavaScript 文件的功能?

我正在使用最新版本的 Angular。提前感谢您的帮助!

标签: javascriptangular

解决方案


不要在 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 文件。无需在每个组件中加载脚本。这会变魔术!!!


推荐阅读