當Server使用.net core SignalR時
Angular可以參考以下寫法
1. 安裝@microsoft/signalr
npm install @microsoft/signalr
2. 新增SignalRService
import { Injectable } from '@angular/core';
import * as signalR from '@microsoft/signalr';
import { environment } from '../../environments/environment';
@Injectable({
providedIn: 'root'
})
export class SignalRService {
private hubConnection: signalR.HubConnection;
StartConnection = () => {
this.hubConnection = new signalR.HubConnectionBuilder()
.withUrl(environment.ApiWebSite + 'baseHub')
.withAutomaticReconnect()
.configureLogging(signalR.LogLevel.Information)
.build();
this.hubConnection
.start()
.then(() => console.log('Connection started'))
.catch(err => console.log('Error while starting connection: ' + err));
}
ReceiveListener(): signalR.HubConnection {
return this.hubConnection;
}
Register(sID: number): void {
console.log(this.hubConnection.state);
this.hubConnection.invoke('Register', sID).then(data => {
console.log(data);
});
}
addTransferChartDataListener = () => {
// 監聽事件
this.hubConnection.on('ReceiveMessage', (data) => {
console.log(data);
});
}
}
3. 修改app.component.ts
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { timer } from 'rxjs';
import { M_BusInfoReturn } from './models/database.model';
import { SignalRService } from './services/signal-r.service';
import { environment } from '../environments/environment';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
listBusInfo = new Array<M_BusInfoReturn>();
systemTime: string;
constructor(public signalRService: SignalRService, private http: HttpClient) {
this.signalRService.StartConnection();
this.signalRService.ReceiveListener().on('SystemTime', (data) => {
this.systemTime = data;
});
this.signalRService.ReceiveListener().on('BusInfo', (data) => {
this.listBusInfo = data;
console.log(this.listBusInfo);
});
}
ngOnInit(): void {
// 5秒後再註冊SignalR
// timer(5000).subscribe(() => {
// this.signalRService.Register(9006);
// });
}
}
參考
- .NET Core with SignalR and Angular – Real-Time Charts
- ASP.NET SignalR 與 ASP.NET Core SignalR 之間的差異
- ASP.NET Core 的 AspNetCore 應用程式
- @microsoft/signalr