【问题标题】:Load scripts through all components in Angular 2通过 Angular 2 中的所有组件加载脚本
【发布时间】:2017-09-27 12:21:48
【问题描述】:

我一直在使用带有 AdminLTE 的 Angular 2,它需要运行一些脚本才能正确加载。所以我在我的 .angular-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"
],

不幸的是,这并非一直有效。该页面第一次加载正常,但是当我路由到另一个页面时,不会为组件模板重新加载脚本。

我找不到任何有关此的信息,这对我来说非常令人惊讶,因为我认为这将是一个普遍的问题!我可能完全迷失了这个!

【问题讨论】:

  • 您可能正在使用一些覆盖它们的脚本
  • 恐怕我根本没有使用任何其他脚本

标签: javascript angular typescript angular2-routing


【解决方案1】:

我发现一个简单的解决方案就是在登录后打开的任何链接中添加window.location.href = '...'。这是我点击登录按钮时的功能。

this.authService.authenticateMember(member).subscribe(data => {
  if (data.success) {
      ...
      window.location.href = '/'
      ...
  } else {
      ...
  }
}

因此,如果您使用身份验证,则可以将上述代码放在登录成功响应的末尾,它会刷新页面并在成功登录后将用户带到他们要去的任何地方。

这不是最好的解决方案,但它是我能想到的最简单的解决方案,因为它需要太多的更改。希望对你有帮助:)

【讨论】:

  • 这是一个非常有趣的解决方案!
【解决方案2】:

您可以在每次需要时在 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 上发布了一个问题,我解释了如何做到这一点。

【讨论】:

    猜你喜欢
    • 2017-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-17
    相关资源
    最近更新 更多