简体   繁体   English

如何在Angular 6中运行第三方JS脚本

[英]How to run third party JS script in Angular 6

I have some third party JS scripts in angular app which has $(document).ready functions, At start everything works fine but when I change the routes via routerLink then some functionality does not work but when page is reloaded then it works. 我在angular应用程序中有一些具有$(document).ready函数的第三方JS脚本,开始时一切正常,但是当我通过routerLink更改路由时,某些功能不起作用,但是当页面重新加载时它起作用。

I have tried importing JS files in angular.json and index.html. 我尝试在angular.json和index.html中导入JS文件。

Please help if you have any solution for this problem. 如果您有解决此问题的方法,请提供帮助。

Thanks. 谢谢。

This happens because the page is fully loaded once and then only portions of the page are re-loaded when you navigate on your routes (SPA). 发生这种情况是因为页面已完全加载一次,然后在您的路线(SPA)上导航时仅重新加载了页面的一部分。 So, the $(document).ready event is fired only once, when the page is loaded. 因此,在加载页面时,只会触发一次$(document).ready事件。

An workaround to achieve this is fire your third party script on your own in some angular life-cycle, for example, angular router NavigationEnd event: 解决此问题的方法是在某个角度生命周期内自行触发第三方脚本,例如,角度路由器NavigationEnd事件:

this.router.events.subscribe(event => {
  if (event instanceof NavigationEnd) {
     // do your stuff here
  }
});

But this is bad, it's easy to lost control. 但这很糟糕,很容易失去控制。 This could be better if you encapsulate the third party library in some Angular component, eg a directive, to avoid $(document).ready pattern. 如果将第三方库封装在某个Angular组件(例如指令)中,以避免$(document).ready模式,则可能会更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM