简体   繁体   English

如何在 Angular2 组件中导入 SignalR?

[英]How to import SignalR in Angular2 component?

I am using angular-cli to scaffold my Angular2 application.我正在使用 angular-cli 来搭建我的 Angular2 应用程序。

Below is the excerpt from my package.json :以下是我的package.json的摘录:

"dependencies": {
    // ...
    "jquery": "^3.1.1",
    "signalr": "^2.2.1"
    //...
},
"devDependencies": {
    // ...
    "@types/jquery": "^2.0.39",
    "@types/signalr": "^2.2.33"
    //...
}

My app.component.ts :我的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($);
    }
}

Now I get the below error from SignalR saying jQuery is not added, but I have imported it in the line above:现在我从 SignalR 得到以下错误,说未添加 jQuery,但我已在上面的行中导入它:

Error: jQuery was not found.错误:未找到 jQuery。 Please ensure jQuery is referenced before the SignalR client JavaScript file.请确保在 SignalR 客户端 JavaScript 文件之前引用 jQuery。

If I comment out import "signalr";如果我注释掉import "signalr"; jQuery gets loaded correctly. jQuery 被正确加载。 What is happening here?这里发生了什么? Why does SignalR say jQuery is not found?为什么 SignalR 说找不到 jQuery?

I solved the issue this way:我这样解决了这个问题:

import $ from 'jquery';
window.jQuery = $;
require('signalr');

Signalr has dependency on window.jQuery . Signalr 依赖于window.jQuery For some reason import $ from 'jquery' doesn't set window.jQuery .出于某种原因import $ from 'jquery'没有设置window.jQuery That's why need to do it explicitly.这就是为什么需要明确地这样做。

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

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