简体   繁体   English

使用 SignalR 的 Angular 2 TypeScript

[英]Angular 2 TypeScript using SignalR

I'm trying to set up an Angular 2 application to use Microsoft's SignalR.我正在尝试设置一个 Angular 2 应用程序以使用 Microsoft 的 SignalR。 I've been following this tutorial , which although it's good I don't like the fact that jQuery and SignalR are loaded into the application via script tags in the index.html file and also the fact that both libraries do not use their respective Type Definitions.我一直在关注本教程,虽然它很好,但我不喜欢通过 index.html 文件中的脚本标签将 jQuery 和 SignalR 加载到应用程序中的事实,以及两个库不使用它们各自的类型的事实定义。

So with that in mind I've been trying to include jQuery and SignalR in my application using node modules and the respective Type Definitions.因此,考虑到这一点,我一直在尝试使用节点模块和相应的类型定义在我的应用程序中包含 jQuery 和 SignalR。 I've searched the correct type definition files to use through Microsoft's TypeSearch .我已经通过 Microsoft 的TypeSearch搜索了要使用的正确类型定义文件。

I'm only including jQuery in my application because of SignalR's dependency on jQuery.由于 SignalR 对 jQuery 的依赖,我只在我的应用程序中包含 jQuery。

jQuery jQuery

I first started with installing the jQuery module in my application which I've had to add in the Webpack configuration as well.我首先在我的应用程序中安装 jQuery 模块,我也必须将其添加到 Webpack 配置中。 After this was set up I'm being faced with a "conflict" issue because of Protractor.设置完成后,由于量角器,我面临“冲突”问题。 This is described on Aurelia JS Rocks' website .这在Aurelia JS Rocks 的网站上有描述。 Although it suggests uninstalling the protractor typings I tried our another solution for now described in this answer .尽管它建议卸载量角器类型,但我尝试了本答案中现在描述的另一种解决方案。 I don't know if this is the best solution.我不知道这是否是最好的解决方案。

SignalR信号R

With regards to SignalR I'm a bit stuck - so far it seems there's no "official" node module provided for SignalR.关于 SignalR 我有点卡住了 - 到目前为止,似乎没有为 SignalR 提供“官方”节点模块。 I'm not sure whether I should include Microsoft's SignalR Javascript Library by downloading the file and including it in my application.我不确定是否应该通过下载文件并将其包含在我的应用程序中来包含 Microsoft 的 SignalR Javascript 库。

The issue is that I have installed the Type Definitions for SignalR.问题是我已经安装了 SignalR 的类型定义。 But now I'm not sure how to go about actually using SignalR since when I type $ or jQuery I'm not being suggested .connections for example - which makes sense as this is not part of the jQuery library.但现在我不知道如何去实际使用SignalR,因为当我输入$jQuery ,我不建议.connections例如-这是有道理的,因为这不是jQuery库的一部分。

I'm sure that I might be misunderstanding something with regards to getting it "set up".我敢肯定,我可能对“设置”它有一些误解。 What's the best way to go about using SignalR in an Angular2 TypeScript application?在 Angular2 TypeScript 应用程序中使用 SignalR 的最佳方法是什么?

Here's a startup code you can use.这是您可以使用的启动代码。

C# C#

//create an interface that contains definition of client side methods
public interface IClient
{
    void messageReceived(string msg);
}

//create your Hub class that contains implementation of client methods
public class ChatHub : Hub<IClient>
{
    public void sendMessage(string msg)
    {
        //log the incoming message here to confirm that its received

        //send back same message with DateTime
        Clients.All.messageReceived("Message received at: " + DateTime.Now.ToString());
    }
}

HTML HTML

Add reference to script files of jQuery and signalR .添加对jQuerysignalR script文件的signalR

<script src="path/to/jquery.min.js"></script>
<script src="path/to/jquery.signalR.min.js"></script>

<!--this is the default path where SignalR generates its JS files so you don't need to change it.-->
<script src="~/signalr/hubs"></script>

JS JS

You need to install TypeScript definition file for SignalR and jQuery .您需要为 SignalR 和 jQuery安装TypeScript 定义文件 If you're using TypeScript 2 , you don't need to add reference to index.d.ts file while using it.如果您使用的是TypeScript 2 ,则无需在使用时添加对index.d.ts文件的引用。 Just install the typings using following commands.只需使用以下命令安装类型。

npm install --save @types/jquery
npm install --save @types/signalr

With all the setup done, you can write a simple TypeScript class to handle the logic for sending and receiving messages.完成所有设置后,您可以编写一个简单的TypeScript class来处理发送和接收消息的逻辑。

export class MessageService {
    //signalR connection reference
    private connection: SignalR;
    
    //signalR proxy reference
    private proxy: SignalR.Hub.Proxy;


    constructor() {
        //initialize connection
        this.connection = $.connection;
        
        //to create proxy give your hub class name as parameter. IMPORTANT: notice that I followed camel casing in giving class name
        this.proxy = $.connection.hub.createHubProxy('chatHub');

        //define a callback method for proxy
        this.proxy.on('messageReceived', (latestMsg) => this.onMessageReceived(latestMsg));

        this.connection.hub.start();
    }
    
    private onMessageReceived(latestMsg: string) {
        console.log('New message received: ' + latestMsg);
    }

    //method for sending message
    broadcastMessage(msg: string) {
        //invoke method by its name using proxy 
        this.proxy.invoke('sendMessage', msg);
    }
}

I'm using the above code, obviously modified to my needs, and it works fine.我正在使用上面的代码,显然根据我的需要进行了修改,并且工作正常。


Update 1: This is a pretty old answer and things have changed a lot since then.更新 1:这是一个非常古老的答案,从那时起事情发生了很大变化。 Install jQuery and SignalR using npm and then load them using angular.json file, like this:使用npm安装jQuerySignalR ,然后使用angular.json文件加载它们,如下所示:

1- Install npm install jquery signalr 1-安装npm install jquery signalr

2- Load in angular.json -> projects -> your-app -> architect -> build -> options 2- 加载angular.json -> projects -> your-app -> architect -> build -> options

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

Thanks and credits to Robert's answer for update.感谢并感谢罗伯特对更新的回答

@Syed Ali Taqi's answer is basically OK but not perfect(even not working if you miss configuring ts compiler). @Syed Ali Taqi 的回答基本可以,但并不完美(如果您错过了配置 ts 编译器,甚至无法正常工作)。 Here's my steps for newest Angular(version 8 as of my writing):这是我最新 Angular 的步骤(我写作时的版本 8):

  1. Install jquery and signalr run time libs: npm install jquery signalr安装 jquery 和 signalr 运行时库: npm install jquery signalr
  2. Tell Angular to load the libs at run time as if they were in the <script></script> tag by configuring angular.json :通过配置 angular.json 告诉 Angular 在运行时加载库,就像它们在<script></script>标签中一样:

     projects: <your-app>: architect: build: options: ... scripts: [ "./node_modules/jquery/dist/jquery.min.js", "./node_modules/signalr/jquery.signalR.min.js" ] ... test: options: ... scripts: [ "./node_modules/jquery/dist/jquery.min.js", "./node_modules/signalr/jquery.signalR.min.js" ]
  3. Install types for jquery and signalr so that the ts compiler can recognize them: npm install @types/jquery @types/signalr --save-dev为 jquery 和 signalr 安装类型,以便 ts 编译器可以识别它们: npm install @types/jquery @types/signalr --save-dev

  4. Tell the ts compiler to load the types by default by editing the types section of tsconfig.app.json and tsconfig.spec.json:通过编辑 tsconfig.app.json 和 tsconfig.spec.json 的types部分,告诉 ts 编译器默认加载类型:
     compilerOptions: types: [..., "jquery", "signalr"]

OK, all done!好了,大功告成! Happy SignalR coding!快乐 SignalR 编码!

let conn = $.hubConnection("<base-path>");
let proxy = conn.createHubProxy("<some-hub>");
...

Note: never try to import ... from jquery explicitly in your code, as said by https://angular.io/guide/using-libraries#using-runtime-global-libraries-inside-your-app注意:永远不要尝试在您的代码中显式地从jquery import ... ,如https://angular.io/guide/using-libraries#using-runtime-global-libraries-inside-your-app所述

For more info on angular.json configuration, see https://angular.io/guide/workspace-config有关 angular.json 配置的更多信息,请参阅https://angular.io/guide/workspace-config

you can try你可以试试

npm install ng2-signalr --save

you can read the setup instructions here ,你可以在这里阅读设置说明,
There is also a link to a working demo .还有一个工作演示的链接。

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

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