我无法使用 Nodejs 使用 Angular + Azure Functions 建立连接。我知道后端可以正常工作,因为我使用以下文档创建了它,并使用文档中提供的客户端 URL 对其进行了测试。消息传递跨多个客户端工作。
所以现在我正试图让 Angular 工作。我已经在 Angular 中为信号器创建了一个服务来建立连接,但是我收到了错误
在网络选项卡上
private buildConnection = () => {
this.hubConnection = new signalR.HubConnectionBuilder()
.withUrl("http://localhost:7070") //use your api adress here and make sure you use right hub name.
.build();
};
使用此代码
private buildConnection = () => {
this.hubConnection = new signalR.HubConnectionBuilder()
.configureLogging(signalR.LogLevel.Debug)
.withUrl("http://localhost:7070/api", {
skipNegotiation: true,
transport: signalR.HttpTransportType.WebSockets
})
.build();
根据这篇文章的推荐答案,但它只是返回
我以前从未使用过 SignalR,所以我试图通过查看几个教程将其拼凑起来。我很感激任何帮助!
信号服务
import { Injectable, EventEmitter } from "@angular/core";
import * as signalR from "@aspnet/signalr";
import { SignalViewModel } from "./signal-view-model";
@Injectable({
providedIn: "root"
})
export class SignalRService {
private hubConnection: signalR.HubConnection;
signalReceived = new EventEmitter<SignalViewModel>();
constructor() {
this.buildConnection();
this.startConnection();
}
private buildConnection = () => {
this.hubConnection = new signalR.HubConnectionBuilder()
.withUrl("http://localhost:7070/api") //c
.build();
};
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);
});
}
}
就像上面的参考文档链接一样,这就是我的天蓝色函数的样子
消息
module.exports = async function (context, req) {
return {
"target": "newMessage",
"arguments": [ req.body ]
};
};
谈判
module.exports = async function (context, req, connectionInfo) {
context.res.json(connectionInfo);
};
主机.json
{
"version": "2.0",
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[1.*, 2.0.0)"
},
"Host": {
"LocalHttpPort": 7070,
"CORS": "http://localhost:4200",
"CORSCredentials": true
}
}