更改路线后,Angular 4脚本不起作用 [英] Angular 4 script not working after changing route
本文介绍了更改路线后,Angular 4脚本不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在更改首页的路由时,javascript和jquery代码未在Angular 5中加载
while changing the routes to homepage, javascript and jquery code is not loading in Angular 5
推荐答案
首先,将脚本添加到.js文件,然后将其保存在angular.json下,如下所示
first, add your script to a .js file and save it under angular.json like below
"scripts": ["src/assets/js/modelsupport.js"],
在您想要它起作用的component.ts中添加以下代码
add below code in you component.ts that you want it to work
URL可以根据您的角度版本以src/assets或资产开头
url could start with src/assets or assets according to your angular version
url = "assets/js/modelsupport.js";
之后,在ngOnInit()或您要调用的任何地方添加以下代码
after that include below code in ngOnInit() or where ever you want to call
this.loadAPI = new Promise(resolve => {
console.log("resolving promise...");
this.loadScript();
});
在您的类中添加loadScript()函数之后
after that add loadScript() function in you class
public loadScript() {
console.log("preparing to load...");
let node = document.createElement("script");
node.src = this.url;
node.type = "text/javascript";
node.async = true;
node.charset = "utf-8";
document.getElementsByTagName("head")[0].appendChild(node);
}
希望您能解决您的问题
这篇关于更改路线后,Angular 4脚本不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文