angular2 typescript ajax,jquery - Angular 2 TypeScript using SignalR - Stack Overflow

本文提供了一段C#和TypeScript代码示例,展示如何使用SignalR创建一个聊天应用。首先定义了一个IClient接口,然后创建了ChatHub类实现客户端方法。接着在HTML中引入jQuery和SignalR的JS文件,并使用TypeScript定义MessageService类来处理发送和接收消息的逻辑。通过$.connection.hub.start()启动连接,并定义回调方法处理接收到的消息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Here's a startup code you can use.

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

Add reference to script files of jQuery and signalR.

JS

You need to install TypeScript definition file for SignalR and jQuery. If you're using TypeScript 2, you don't need to add reference to index.d.ts file while using it. 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.

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. Install jQuery and SignalR using npm and then load them using angular.json file, like this:

1- Install npm install jquery signalr

2- Load in 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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值