我正在使用 angular-cli 搭建我的 Angular2 应用程序。
下面是我的 package.json
的摘录:
"dependencies": {
// ...
"jquery": "^3.1.1",
"signalr": "^2.2.1"
//...
},
"devDependencies": {
// ...
"@types/jquery": "^2.0.39",
"@types/signalr": "^2.2.33"
//...
}
我的app.component.ts
:
import { Component } from '@angular/core';
import * as $ from "jquery";
import "signalr";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app works!';
constructor() {
console.log($);
}
}
现在我从 SignalR 得到以下错误,说没有添加 jQuery,但我已经在上面的行中导入了它:
Error: jQuery was not found. Please ensure jQuery is referenced before the SignalR client JavaScript file.
如果我注释掉 import "signalr";
jQuery 会正确加载。这里发生了什么?为什么 SignalR 说找不到 jQuery?
最佳答案
我是这样解决问题的:
import $ from 'jquery';
window.jQuery = $;
require('signalr');
Signalr 依赖于 window.jQuery
。由于某些原因,import $ from 'jquery'
没有设置 window.jQuery
。这就是为什么需要明确地这样做。
关于javascript - 如何在 Angular2 组件中导入 SignalR?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41791118/