Load scripts through all components in Angular 2

北城余情 提交于 2019-12-30 07:25:11

问题


I have been using Angular 2 with AdminLTE which needs to run some scripts to load properly. So I have added them in in my .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"
],

Unfortunately, this does not work all time. The page loads fine the first time but when I route to another page, scripts are not reloaded for the component template.

I could not find any information about this which is very surprising for me since I thought it would be a general problem! I might be totally lost with this!


回答1:


You can remove and recreate your script elements in DOM every time you need, like this:

document.getElementById("myScript").remove();
var testScript = document.createElement("script");
testScript.setAttribute("id", "myScript");
testScript.setAttribute("src", "assets/js/script.js");
document.body.appendChild(myScript);

I posted a question in GitHub where I explain how to do it.




回答2:


A simple solution I found was just to add a window.location.href = '...' to whatever link you are opening after login. Heres my function for the when the login button is clicked.

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

So if you are using authentication then you can put that above code at the end of your login success response and it will refresh the page aswell as take the user to wherever they are going after a successful login.

This is not the best solution but it is the simplest one i can think of that dosent require too many changes. Hope it helps :)



来源:https://stackoverflow.com/questions/46447754/load-scripts-through-all-components-in-angular-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!