【发布时间】:2020-07-03 00:41:32
【问题描述】:
我正在尝试订阅我发送的消息,但它在浏览器中一直返回 null
SignalR 连接已经建立,我可以发送消息,但它没有订阅任何更改。这是为什么呢?
SignalR 服务
import { Injectable, EventEmitter } from "@angular/core";
import * as signalR from "@aspnet/signalr";
import { SignalViewModel } from "./signal-view-model";
import { HttpClient, HttpParams } from "@angular/common/http";
@Injectable({
providedIn: "root"
})
export class SignalRService {
private hubConnection: signalR.HubConnection;
signalReceived = new EventEmitter<SignalViewModel>();
constructor(private http: HttpClient) {
this.buildConnection();
this.startConnection();
}
private buildConnection = () => {
this.hubConnection = new signalR.HubConnectionBuilder()
.withUrl("http://localhost:7070/api")
.build();
}
sendMessage(message: SignalViewModel) {
this.http.post('http://localhost:7070/api/messages', message).subscribe(data => console.log(data));
}
private startConnection = () => {
this.hubConnection
.start()
.then(() => {
console.log("Connection Started...");
this.registerSignalEvents();
})
.catch(err => {
console.log("Error while starting connection: " + err);
//if you get error try to start connection again after 3 seconds.
setTimeout(function () {
this.startConnection();
}, 3000);
});
}
private registerSignalEvents() {
this.hubConnection.on("SignalMessageReceived", (data: SignalViewModel) => {
this.signalReceived.emit(data);
});
}
}
信号视图模型
export class SignalViewModel {
clientuniqueid: string;
type: string;
message: string;
date: Date;
}
组件
notificationSubscription: Subscription;
ngOnInit() {
this.signalRService.signalReceived.subscribe(msg => {
this.messages.push(msg);
console.log(this.messages)
});
//I also tried it like the following, but same issue
this.notificationSubscription = this.signalRService.signalReceived.subscribe(msg => {
this.messages.push(msg);
console.log(this.messages)
})
...
我怎样才能让它订阅成功?感谢您的帮助!
【问题讨论】:
标签: angular azure signalr azure-functions