如何在 Angular 8 应用程序中使用 jQuery? [英] How can I use jQuery in an Angular 8 app?

查看:23
本文介绍了如何在 Angular 8 应用程序中使用 jQuery?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,它利用 SignalR 与桌面应用程序进行通信.要使用 SignalR,我需要在我的 .ts 文件中使用 jQuery.但是,从 Angular 7 迁移到 Angular 8 后,它似乎不起作用.

I have an application that utilizes SignalR to communicate with a desktop application. To utilize SignalR I need to use jQuery in my .ts file. However, it doesn't seem to work post migrating from Angular 7 to Angular 8.

我使用 declare var $: any; 就像我在以前的 Angular 版本中一样.不幸的是,$ 现在在控制台打印空白.

I use declare var $: any; as I have in previous versions of Angular. Unfortunately, $ now prints blank to the console.

那么,Angular v8 是不再支持以这种方式使用 jQuery,还是在迁移过程中发生了其他问题?

So, does Angular v8 no longer support using jQuery this way, or did something else break in the migration?

更新:

我通过 npm 加载了 jQuery v3.3.1.

I have jQuery v3.3.1 loaded via npm.

这使它成为全局的(在 angular.json 中)

This makes it global (in angular.json)

"scripts": [
         "./node_modules/jquery/dist/jquery.min.js",
         "./node_modules/signalr/jquery.signalR.js"
]

推荐答案

所以,在暂时离开这个问题并使用 roberts answer 确认 jQuery 在 app.module.ts 中工作之后(我不知道console.log 可以在导入过程中工作),我意识到我上次将 v4 升级到 v7 时遇到了这个问题.

So, after stepping away from the issue for a bit and using roberts answer to confirm jQuery was working in app.module.ts (I wasn't aware a console.log would work in the middle of the imports), I realized I had fought this issue the last time I upgraded v4 to v7.

发生的事情是依赖项导致 jQuery 被重新加载.启动 signalR 通信的应用程序部分还加载了另一个依赖项 (telerik-angular-report-viewer),它导致 console.log($) 不显示任何内容,因为 jQuery 尚未加载到组件中.

What had happened, is a dependency was causing jQuery to be reloaded. The section of the app that starts the signalR communication also loads another dependency (telerik-angular-report-viewer) which was causing console.log($) to display nothing because jQuery hadn't been loaded into the component yet.

修复:

去掉下面的代码

window.jQuery = jQuery;
window.$ = jQuery;

来自以下文件

  • dependencies\telerikReportViewer.kendo.min.js
  • dependencies\telerikReportViewer.js
  • cjs\telerik-report-viewer.component.js
  • es\telerik-report-viewer.component.js

这篇关于如何在 Angular 8 应用程序中使用 jQuery?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆