公司开发需要使用signalr来实现消息广播,查阅很多资料,和后端配合,基本实现效果
npm install --save @aspnet/signalr
npm install --save @types/signalr
proxy.json 这里错了容易出一堆错误
{
"/hubs": {
"target": "http://xxxx.xxxx.com",
"changeOrigin": true, // 重要点
"ws": true // 重要点
}
}
signalr.service.ts
import { Injectable } from '@angular/core';
import * as signalR from "@aspnet/signalr"; // 重点
@Injectable({
providedIn: 'root'
})
export class SignalrService {
public connnectSignal(url: string, token?: string = ''): void {
const that = this;
const connection = new signalR.HubConnectionBuilder().withUrl(url, {
accessTokenFactory: () =>
token
}).build();
connection.on("ReceiveMessage", function (message) {
//服务端发过来的消息
console.log(message);
});
connection.start().then(function () {
console.log('成功');
}).catch(function (err) {
setTimeout(() => {
that.connnectSignal(url);
},1000)
return console.error(err.toString());
});
}
}
在页面调用时
this._signalrService.connnectSignal('/hubs/message', this._token);
很多功能还要后端那边处理 ,所以后端还是很辛苦的,在这里感谢下我们的后端
本文记录了在Angular项目中使用SignalR实现消息广播的过程。通过详细描述配置proxy.json和编写signalr.service.ts文件的要点,以及在页面中调用SignalR服务的方法,展现了与后端配合实现功能的步骤。同时,文中表达了对后端开发人员辛勤工作的感激之情。
533

被折叠的 条评论
为什么被折叠?



