Angular未订阅SignalR消息
创始人
2024-10-29 22:30:50
0

在Angular中订阅SignalR消息,可以使用RxJS的Observable和Subject来处理。下面是一个示例代码:

首先,确保已经安装了SignalR和RxJS的依赖:

npm install @aspnet/signalr rxjs --save

在Angular的组件中,创建一个SignalR服务:

import { Injectable } from '@angular/core';
import * as signalR from '@aspnet/signalr';
import { Observable, Subject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class SignalRService {
  private hubConnection: signalR.HubConnection;
  private messageSubject: Subject = new Subject();

  constructor() {
    this.hubConnection = new signalR.HubConnectionBuilder()
      .withUrl('')
      .configureLogging(signalR.LogLevel.Information)
      .build();

    this.hubConnection.start().catch(err => console.error(err));

    this.hubConnection.on('ReceiveMessage', (message: string) => {
      this.messageSubject.next(message);
    });
  }

  public getMessages(): Observable {
    return this.messageSubject.asObservable();
  }
}

在组件中使用SignalR服务:

import { Component, OnInit } from '@angular/core';
import { SignalRService } from './signalr.service';

@Component({
  selector: 'app-root',
  template: `
    
{{ message }}
` }) export class AppComponent implements OnInit { public messages: string[] = []; constructor(private signalRService: SignalRService) {} ngOnInit(): void { this.signalRService.getMessages().subscribe(message => { this.messages.push(message); }); } }

在上面的代码中,SignalR服务创建了一个messageSubject,用于发布接收到的消息。在组件中通过调用getMessages方法,订阅了这个Subject,并将接收到的消息添加到messages数组中。

这样就可以在Angular中订阅SignalR消息了。

相关内容

热门资讯

wepoke是真的有挂!wpk... wepoke是真的有挂!wpk数据清零,(wePOke)切实是有挂(详细透视可靠教程);是一款可以让...
wpk德州透视辅助!约局吧有辅... wpk德州透视辅助!约局吧有辅助吗,(来玩德州)素来存在有挂(详细透视力荐教程);1分钟了解详细教程...
德扑ai智能!we poke有... 1、德扑ai智能!we poke有挂吗,(wepOkE)本然是真的有挂(详细辅助解说技巧);详细教程...
微扑克全自动机器人!poker... 微扑克全自动机器人!pokernow怎么开挂,(WEPOke)总是是有挂(详细透视必赢教程);亲们利...
aapoker透明挂!wpk有... aapoker透明挂!wpk有猫腻吗,(wePOke)一直存在有挂(详细辅助扑克教程)是一款可以让一...
德州AI智能辅助机器人!微扑克... 德州AI智能辅助机器人!微扑克有没有稳赢的打法,(wEPoke)往昔真的有挂(详细辅助力荐教程)是一...
德州之星插件!wpk数据清零,... 德州之星插件新手教程相关信息汇总(需添加指定Q群1067239143获取下载链接);德州之星插件!w...
德扑数据软件!哈糖大菠萝有外挂... 德扑数据软件!哈糖大菠萝有外挂吗,(WepOke)固有真的有挂(详细透视AI教程);1分钟了解详细教...
aapoker透明挂!aa p... aapoker透明挂!aa poker有没有挂,(Wepoke)原来真的是有挂(详细辅助教你攻略)是...
德扑之星有作弊!德扑之星有没有... WePoke高级策略深度解析‌;德扑之星有作弊!德扑之星有没有规律,(WpK)切实真的是有挂(详细透...