我尝试通过聊天重复示例。 Such here。但是当我取消请求时,我对房东的地址有疑问。这就是组件启动时的状态。
您可以看到我有两次地址。我只尝试了/chat
,但结果相同
我在VS中启动的应用。我不作为一个单独的客户端部分开始使用并且没有api限制。
这是我的应用程序的网络地址,我从这里开始聊天。 http://localhost:59955/home/message
我的代码
public class ChatHub : Hub
{
public async Task Send(string name, string message)
{
await this.Clients.All.SendAsync("sendToAll", name, message);
}
}
启动和我添加的内容。
services.AddSignalR();
services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
{
builder
.AllowAnyMethod()
.AllowAnyHeader()
.WithOrigins("http://localhost:4200");
}));
然后我使用public void Configure(IApplicationBuilder app, IHostingEnvironment env)
app.UseSignalR(routes =>
{
routes.MapHub<Chat>("/chat");
});
现在是客户端
export class ChatComponent implements OnInit {
// tslint:disable-next-line:variable-name
private _hubConnection: HubConnection;
nick = '';
message = '';
messages: string[] = [];
constructor() { }
ngOnInit() {
this.nick = window.prompt('Your name:', 'John');
this._hubConnection = new
HubConnectionBuilder().withUrl('http://localhost:59955/chat').build();
this._hubConnection
.start()
.then(() => console.log('Connection started!'))
.catch(err => console.log('Error while establishing connection :('));
}
public sendMessage(): void {
this._hubConnection.on('sendToAll', (nick: string, receivedMessage: string)
=> {
const text = `${nick}: ${receivedMessage}`;
this.messages.push(text);
});
this._hubConnection
.invoke('sendToAll', this.nick, this.message)
.catch(err => console.error(err));
}
}
有launchSettings json文件。
什么问题?
答案 0 :(得分:0)
我试图从头开始在同一项目中创建SignalR集线器服务器和Angular客户端,使用相同的代码创建集线器服务器并配置SignalR。
对于Angular客户端,我发现此软件包“ @ aspnet / signalr-client ”已被弃用,因此我改用“ @ aspnet / signalr ”。< / p>
该项目在我这方面运行良好,没有错误,如果可能,您可以创建新项目或使用' @ aspnet / signalr '构建SignalR Angular客户端并检查它是否对您有用。< / p>
Angular客户
import { Component, OnInit } from '@angular/core';
import { HubConnection } from '@aspnet/signalr';
import signalR = require('@aspnet/signalr');
@Component({
selector: 'app-signalrchatroom',
templateUrl: './signalrchatroom.component.html',
styleUrls: ['./signalrchatroom.component.css']
})
export class SignalrchatroomComponent implements OnInit {
constructor() { }
private _hubConnection: HubConnection;
nick = '';
message = '';
messages: string[] = [];
ngOnInit() {
this.nick = window.prompt('Your name:', 'John');
this._hubConnection = new signalR.HubConnectionBuilder()
.withUrl("/chat")
.build();
this._hubConnection
.start()
.then(() => console.log('Connection started!'))
.catch(err => console.log('Error while establishing connection :('));
this._hubConnection.on('sendToAll', (nick: string, receivedMessage: string) => {
const text = `${nick}: ${receivedMessage}`;
this.messages.push(text);
});
}
public sendMessage(): void {
this._hubConnection
.invoke('sendToAll', this.nick, this.message)
.catch(err => console.error(err));
}
}
测试结果