通过 Angular 中的所有组件加载脚本 2
Load scripts through all components in Angular 2
我一直在使用 Angular 2 和 AdminLTE,这需要 运行 一些脚本才能正确加载。所以我在 .anglular-cli.json:
中添加了它们
"scripts": [
"../node_modules/jquery/dist/jquery.min.js",
"../node_modules/bootstrap/dist/js/bootstrap.min.js",
"../node_modules/admin-lte/dist/js/adminlte.min.js",
"../node_modules/moment/min/moment.min.js"
],
不幸的是,这并非一直有效。页面第一次加载正常,但当我路由到另一个页面时,组件模板的脚本没有重新加载。
我找不到任何关于这个的信息,这让我感到非常惊讶,因为我认为这将是一个普遍的问题!我可能完全迷失了这个!
您可以在每次需要时删除并重新创建 DOM 中的脚本元素,如下所示:
document.getElementById("myScript").remove();
var testScript = document.createElement("script");
testScript.setAttribute("id", "myScript");
testScript.setAttribute("src", "assets/js/script.js");
document.body.appendChild(myScript);
我在 GitHub 中发布了一个问题,解释了如何做。
我发现一个简单的解决方案就是在登录后打开的 link 中添加一个 window.location.href = '...'
。这是单击登录按钮时的函数。
this.authService.authenticateMember(member).subscribe(data => {
if (data.success) {
...
window.location.href = '/'
...
} else {
...
}
}
因此,如果您使用身份验证,那么您可以将上述代码放在登录成功响应的末尾,它将刷新页面并在成功登录后将用户带到他们要去的任何地方。
这不是最好的解决方案,但它是我能想到的最简单的解决方案,因为剂量需要太多更改。希望对您有所帮助:)
我一直在使用 Angular 2 和 AdminLTE,这需要 运行 一些脚本才能正确加载。所以我在 .anglular-cli.json:
中添加了它们"scripts": [
"../node_modules/jquery/dist/jquery.min.js",
"../node_modules/bootstrap/dist/js/bootstrap.min.js",
"../node_modules/admin-lte/dist/js/adminlte.min.js",
"../node_modules/moment/min/moment.min.js"
],
不幸的是,这并非一直有效。页面第一次加载正常,但当我路由到另一个页面时,组件模板的脚本没有重新加载。
我找不到任何关于这个的信息,这让我感到非常惊讶,因为我认为这将是一个普遍的问题!我可能完全迷失了这个!
您可以在每次需要时删除并重新创建 DOM 中的脚本元素,如下所示:
document.getElementById("myScript").remove();
var testScript = document.createElement("script");
testScript.setAttribute("id", "myScript");
testScript.setAttribute("src", "assets/js/script.js");
document.body.appendChild(myScript);
我在 GitHub 中发布了一个问题,解释了如何做。
我发现一个简单的解决方案就是在登录后打开的 link 中添加一个 window.location.href = '...'
。这是单击登录按钮时的函数。
this.authService.authenticateMember(member).subscribe(data => {
if (data.success) {
...
window.location.href = '/'
...
} else {
...
}
}
因此,如果您使用身份验证,那么您可以将上述代码放在登录成功响应的末尾,它将刷新页面并在成功登录后将用户带到他们要去的任何地方。
这不是最好的解决方案,但它是我能想到的最简单的解决方案,因为剂量需要太多更改。希望对您有所帮助:)