使用SignalR的Angular 2 TypeScript

我正在尝试设置一个Angular 2应用程序来使用Microsoft的SignalR。 我一直在关注这个教程 ,虽然它很好但我不喜欢jQuery和SignalR通过index.html文件中的脚本标签加载到应用程序中的事实,以及两个库都不使用它们各自的类型这一事实定义。

因此,考虑到这一点,我一直在尝试使用节点模块和相应的类型定义在我的应用程序中包含jQuery和SignalR。 我通过微软的TypeSearch搜索了正确的类型定义文件。

我只在我的应用程序中包含jQuery,因为SignalR依赖于jQuery。

jQuery的

我首先开始在我的应用程序中安装jQuery模块,我必须在Webpack配置中添加它。 在此之后,由于量角器,我面临着“冲突”问题。 这在Aurelia JS Rocks的网站上有所描述。 虽然它建议卸载量角器类型,但我尝试了另一个解决方案,现在在这个答案中描述 。 我不知道这是不是最好的解决方案。

SignalR

关于SignalR,我有点卡住了 – 到目前为止,似乎没有为SignalR提供“官方”节点模块。 我不确定是否应该通过下载文件并将其包含在我的应用程序中来包含Microsoft的SignalR Javascript库。

问题是我已经安装了SignalR的类型定义。 但是现在我不确定如何实际使用SignalR,因为当我键入$jQuery我没有被建议。例如.connections – 这是有意义的,因为这不是jQuery库的一部分。

我确信我可能会误解一些关于“设置”的问题。 在Angular2 TypeScript应用程序中使用SignalR的最佳方法是什么?

这是您可以使用的启动代码。

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 { 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

添加对jQuerysignalR script文件的signalR

     

JS

您需要为SignalR和jQuery安装TypeScript定义文件 。 如果您使用的是TypeScript 2 ,则在使用时不需要添加对index.d.ts文件的引用。 只需使用以下命令安装打字机。

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

完成所有设置后,您可以编写一个简单的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); } } 

我正在使用上面的代码,显然已根据我的需要进行了修改,并且工作正常。

你可以试试

 npm install ng2-signalr --save 

你可以在这里阅读设置说明,
还有一个工作演示的链接。